Dapper Multi-map next level

时光怂恿深爱的人放手 提交于 2019-12-03 12:34:54

Dapper allows you to map a single row to multiple objects, so you can just map SiteOu as part of the same query.

[Test]
public void TestSplitOn()
{
    var conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=db");
    conn.Open();
    const string sql = "select Id = 1, Name = 'My Part', " +
                       "Id = 2, Street = 'My Street', " +
                       "Id = 3, Name = 'My Site'";
    var result = conn.Query<Part, Address, SiteOu, Part>(sql, (part, address, siteOu) =>
    {
        part.Address = address;
        address.Ou = siteOu;
        return part;
    },
    commandType: CommandType.Text
    ).FirstOrDefault();

    Assert.That(result, Is.Not.Null);
    Assert.That(result.Address, Is.Not.Null);
    Assert.That(result.Address.Ou, Is.Not.Null);
}

Important Note: Dapper assumes your Id columns are named "Id" or "id", if your primary key is different or you would like to split the wide row at point other than "Id", use the optional 'splitOn' parameter.

If you have more that 5 types to map, another out of the box option is to use QueryMultiple extension. Here is an example from the Dapper docs.

var sql = 
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id";

using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
   var customer = multi.Read<Customer>().Single();
   var orders = multi.Read<Order>().ToList();
   var returns = multi.Read<Return>().ToList();
   ...
} 

Also check out this thread.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!