Dapper 查询一对多关系
Dapper Query One To Many Relation
我在将查询映射到模型时遇到问题。
每个 TaxId 都有很多商户,但是当我使用 Dapper 进行映射时,属性 商户是空的。该模型有一个 TaxId、一个商家列表和一个卡片品牌。
型号
public class LeadModel
{
public string TaxId { get; set; }
public IEnumerable<string> Merchants { get; set; }
public string CardBrand { get; set; }
}
查询
SELECT "RegistrationNumber" as "TaxId"
, jsonb_agg("MerchantReference") as "Merchant"
, 'X' as "CardBrand"
FROM "Merchant"
WHERE "MerchantId" in...
数据库查询
TaxId
Merchant
CardBrand
77777777777777
101010101000000
X
12345678901234
202020202000000
X
77777777777777
303030303000000
X
77777777777777
404040404000000
X
12345678901234
505050505000000
X
代码
var leadModels = _dbConnection.Query<string, List<string>, LeadModel>(sql, (taxId, merchants) =>
{
LeadModel leadModel = new LeadModel();
leadModel.TaxId = taxId;
leadModel.Merchants = merchants;
leadModel.CardBrand = cardBrand;
return leadModel;
}, dynamicParameters, splitOn: "cardBrand")
.ToList();
当前结果
参考文献:https://dapper-tutorial.net/query#example-query-multi-mapping-one-to-many
主要变化是:
- 查询参数
- 从字符串列表反序列化到商家 属性 (
IEnumerable<string>
)
- 添加
splitOn
列
结果:
var leadModels = _dbConnection.Query<string, string, string, LeadModel>(sql, (taxId, merchant, cardBrand) =>
{
LeadModel leadModel = new LeadModel();
leadModel.TaxId = taxId;
leadModel.Merchants = JsonConvert.DeserializeObject<List<string>>(merchant);
leadModel.CardBrand = cardBrand;
return leadModel;
}, dynamicParameters, splitOn: "TaxId,Merchant,CardBrand")
.ToList();
我在将查询映射到模型时遇到问题。
每个 TaxId 都有很多商户,但是当我使用 Dapper 进行映射时,属性 商户是空的。该模型有一个 TaxId、一个商家列表和一个卡片品牌。
型号
public class LeadModel
{
public string TaxId { get; set; }
public IEnumerable<string> Merchants { get; set; }
public string CardBrand { get; set; }
}
查询
SELECT "RegistrationNumber" as "TaxId"
, jsonb_agg("MerchantReference") as "Merchant"
, 'X' as "CardBrand"
FROM "Merchant"
WHERE "MerchantId" in...
数据库查询
TaxId | Merchant | CardBrand |
---|---|---|
77777777777777 | 101010101000000 | X |
12345678901234 | 202020202000000 | X |
77777777777777 | 303030303000000 | X |
77777777777777 | 404040404000000 | X |
12345678901234 | 505050505000000 | X |
代码
var leadModels = _dbConnection.Query<string, List<string>, LeadModel>(sql, (taxId, merchants) =>
{
LeadModel leadModel = new LeadModel();
leadModel.TaxId = taxId;
leadModel.Merchants = merchants;
leadModel.CardBrand = cardBrand;
return leadModel;
}, dynamicParameters, splitOn: "cardBrand")
.ToList();
当前结果
参考文献:https://dapper-tutorial.net/query#example-query-multi-mapping-one-to-many
主要变化是:
- 查询参数
- 从字符串列表反序列化到商家 属性 (
IEnumerable<string>
) - 添加
splitOn
列
结果:
var leadModels = _dbConnection.Query<string, string, string, LeadModel>(sql, (taxId, merchant, cardBrand) =>
{
LeadModel leadModel = new LeadModel();
leadModel.TaxId = taxId;
leadModel.Merchants = JsonConvert.DeserializeObject<List<string>>(merchant);
leadModel.CardBrand = cardBrand;
return leadModel;
}, dynamicParameters, splitOn: "TaxId,Merchant,CardBrand")
.ToList();