我有2类,分别是Order和Address:



public class Order
{
    public string OrderId { get; set; }
    public Address ShippingAddress { get; set; }
    public Address BillingAddress { get; set; }
}






public class Address
{
    public string Street { get; set; }
    public string Town { get; set; }
    public string Zip { get; set; }
}


数据库将订单和地址存储在单个表中,如下所示:


CREATE TABLE Orders
    (
        OrderId NVARCHAR(56) PRIMARY KEY,
        BillingStreet NVARCHAR(256),
        BillingTown NVARCHAR(256),
        BillingZip NVARCHAR(256),
        ShippingStreet NVARCHAR(256),
        ShippingTown NVARCHAR(256),
        ShippingZip NVARCHAR(256)
    )


c# - 列名称中带有前缀的Dapper映射-LMLPHP

我如何获得dapper将此映射到Order类?

最佳答案

通过使查询对帐单和发运列进行一般化,并使用具有多种类型的Query版本,并在看到名为“地址”的列时告诉它进行拆分,可以通过以下方法来实现此目的。然后,您只需将Address对象分配给Order对象上的适当属性。

connection.Query<Order, Address, Address, Order>(
    @"SELECT OrderId,
             BillingAddress As Address,
             BillingTown As Town,
             BillingZip As Zip,
             ShippingAddress As Address,
             ShippingTown As Town,
             ShippingZip As Zip,
      FROM Orders",
    (o, ba, sa) =>
    {
        o.BillingAddress = ba;
        o.ShippingAddress = sa;
        return o;
    },
    splitOn: "Address");

关于c# - 列名称中带有前缀的Dapper映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34434826/

10-16 21:10