使用Dapper MultiMapper和外部联接查询

时间:2015-04-03 17:40:38

标签: c# dapper

这是我第一次使用Dapper,我正在努力实现以下目标

我们将域对象定义为

public class Company
{
    public Int64 company_id { get; set; }

    public ICollection<Brand> Brands { get; set; }

    public ICollection<CompanyConnector> CompanyConnectors { get; set; }
}

public class Brand
{
    public Int64 brand_id { get; set; }

    public Int64 company_id { get; set; }

    public string brand_name { get; set; }
}

public class CompanyConnector
{
    public Int64 company_connector_id { get; set; }

    public Int64 company_id { get; set; }
}

我正在尝试使用Dapper中的多映射器来获取公司,所有品牌(这是可选的)和所有连接器(也可选)。

我有左外连接的查询

select company.*, brand.* , company_connector.*
from company 
left outer join brand on company.company_id = brand.company_id
left outer join company_connector on company.company_id=        company_connector.company_id

获取数据的代码是

var lookup = new Dictionary<Int64, Company>();
connection.Query<Company, Brand, CompanyConnector, Company>(strQuery,
(c, b, cc) =>
{
    Company cm;
    if (!lookup.TryGetValue(c.company_id, out cm))
    {
        lookup.Add(c.company_id, cm = c);
    }

    if (null != b)
    {
        if (null == cm.Brands)
            cm.Brands = new List<Brand>();
        cm.Brands.Add(b);
    }

    if (null != cc)
    {
        if (null == cm.CompanyConnectors)
            cm.CompanyConnectors = new List<CompanyConnector>();
        cm.CompanyConnectors.Add(cc);
    }

    return cm;
}, splitOn: "brand_id, company_connector_id"
).AsQueryable();

由于公司有2个品牌和2个连接器 - 外连接产生4行 - 因此结果对象有4个品牌条目和4个连接器条目

我可以在添加到列表

之前添加代码行来检查对象是否存在
if(!cm.Brands.Any(item => item.brand_id == b.brand_id))
cm.Brands.Add(b);

问题 - 我是否正确使用此方法?对于我来说,获得正确数量的品牌记录和连接器记录的解决方案是什么?

1 个答案:

答案 0 :(得分:2)

从我收集的内容来看,Dapper并不直接支持加载子集合,这就是为什么你有代码进行查找,检查null,添加值......

我刚刚在那里添加了一张支票,以查看该值是否已添加到集合中。

var lookup = new Dictionary<Int64, Company>();
connection.Query<Company, Brand, CompanyConnector, Company>(strQuery,
(c, b, cc) =>
{
    Company cm;
    if (!lookup.TryGetValue(c.company_id, out cm))
    {
        lookup.Add(c.company_id, cm = c);
    }

    if (null != b)
    {
        if (null == cm.Brands)
            cm.Brands = new List<Brand>();
        if(!cm.Brands.Any(r=>r.brand_id == b.brand_id ))
            cm.Brands.Add(b);
    }

    if (null != cc)
    {
        if (null == cm.CompanyConnectors)
            cm.CompanyConnectors = new List<CompanyConnector>();
        if(!cm.CompanyConnectors.Any(r=>r.company_connector_id  == b.company_connector_id  ))
            cm.CompanyConnectors.Add(cc);
    }

    return cm;
}, splitOn: "company_id, brand_id, company_connector_id"
).AsQueryable();

可以做的另一件事是分开加载3个集合并将它们映射到精巧的函数之外。

select * from company
select * from brand b join company c on c.company_id = b.company_id
select * from company_connector b join company c on c.company_id = b.company_id