Dapper Multi-map下一级 [英] Dapper Multi-map next level

查看:67
本文介绍了Dapper Multi-map下一级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为当前查询使用多个映射,现在我需要在初始查询上映射另一个对象。

I'm using multiple mapping for a current query and now I need to map another object on the initial query.

例如:

public class Part {
  public int Id { get; set; }
  public string Name { get; set; }

  public Address Address { get; set; }

}

public class Address {
  public int Id { get; set; }
  public string Street { get; set; }

  public SiteOu Ou { get; set; }
}

public class SiteOu 
  public int Id { get; set; }
  public string Name { get; set; }
}

Dapper:

 connection.Query<Part, Address, Part>(sql, (part, address) => {
    part.Address = address;
  });

如何获取Address类以获取SiteOu信息?

How do I get the Address class to have the SiteOu information?

这个示例并不是我真正在做的,因为我确实拥有

This example isn't what I'm actually doing because I've actually got

Query<T1,T2,T3,T4,T5,TResult>();  

我在查询中进行了1次选择和5次连接。因此,希望我不需要更多的Query重载。

I'm doing 1 select and 5 joins in my query. So hopefully I don't need more overloads of Query.

推荐答案

Dapper允许您将单行映射到多个对象,因此您可以将SiteOu映射为同一查询的一部分。

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);
}

重要说明: Dapper 假设您的Id列名为 Id或 id,如果您的主键不同或您想在 Id以外的其他位置拆分宽行,请使用可选的'splitOn'参数。

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.

如果要映射的类型超过5种,则另一个现成的选项是使用QueryMultiple扩展名。这是Dapper文档中的示例。

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();
   ...
} 

也请查看线程

这篇关于Dapper Multi-map下一级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆