使用Dapper映射多个复杂类型属性

时间:2019-01-30 08:30:21

标签: c# .net orm dapper

我有以下Dapper查询:

var orderModels = db.Query<OrderModel>(@"
SELECT
    o.[Id],
    o.[CustomerId],

    o.[DeliveryAddress_FirstName],
    o.[DeliveryAddress_LastName],
    o.[DeliveryAddress_Line1],
    o.[DeliveryAddress_Line2],
    o.[DeliveryAddress_City],
    o.[DeliveryAddress_State],
    o.[DeliveryAddress_PostCode],
    o.[DeliveryAddress_Country],

    o.[BillingAddress_FirstName],
    o.[BillingAddress_LastName],
    o.[BillingAddress_Line1],
    o.[BillingAddress_Line2],
    o.[BillingAddress_City],
    o.[BillingAddress_State],
    o.[BillingAddress_PostCode],
    o.[BillingAddress_Country]
FROM
    [Order] o
");

我想将其加载到以下结构的数据模型中:

public class OrderModel
{
    public int Id { get; set; }
    public int CustomerId { get; set; }

    public AddressModel DeliveryAddress { get; set; }
    public AddressModel BillingAddress { get; set; }
}

public class AddressModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostCode { get; set; }
    public string Country { get; set; }
}

我已经尝试过查找,并且有一个feature in Dapper called multi-mapping。但是,当我不联接多个表的结果时,我不知道如何在用例中使用它。

对于像Dapper这样的ORM,这感觉很普遍,所以我确定我只是缺少明显的东西。如果您更了解Dapper,请提供帮助。

什么是最好的方法?

1 个答案:

答案 0 :(得分:2)

Dapper不在乎联接,您只需要为splitOn选项提供正确的字段即可,例如:

    var orderModels = db.Query<OrderModel, AddressModel, AddressModel, OrderModel>(@"
    SELECT
        o.[Id],
        o.[CustomerId],

        o.[DeliveryAddress_FirstName] AS [FirstName], // Field names should match properties of your model
        o.[DeliveryAddress_LastName] AS [LastName],
        o.[DeliveryAddress_Line1] AS [Line1],
        o.[DeliveryAddress_Line2] AS [Line2],
        o.[DeliveryAddress_City] AS [City],
        o.[DeliveryAddress_State] AS [State],
        o.[DeliveryAddress_PostCode] AS [PostCode],
        o.[DeliveryAddress_Country] AS [Country],

        o.[BillingAddress_FirstName] AS [FirstName],
        o.[BillingAddress_LastName] AS [LastName],
        o.[BillingAddress_Line1] AS [Line1],
        o.[BillingAddress_Line2] AS [Line2],
        o.[BillingAddress_City] AS [City],
        o.[BillingAddress_State] AS [State],
        o.[BillingAddress_PostCode] AS [PostCode],
        o.[BillingAddress_Country] AS [Country]
    FROM
        [Order] o
    ", 
(order, deliveryAddress,  billingAddress) => {
   order.DeliveryAddress = deliveryAddress; 
   order.BillingAddress = billingAddress; 
   return order; 
},
splitOn: "FirstName,FirstName");

它在this article中有解释。

此外,所选内容的字段名称必须与模型属性名称匹配,Dapper才能自动找出映射。