我有两个课程,顺序和地址如下:
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)
)
如何让dapper将其映射到Order类?
答案 0 :(得分:2)
以下是如何通过使查询概括计费和发货列以及使用多个类型的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");
答案 1 :(得分:0)
我认为Dapper不可能,因为它将行视为单个对象。如果你想改变你的表结构,那就有可能:
CREATE TABLE Orders
(
OrderId NVARCHAR(56) PRIMARY KEY,
BillingAddressId INT
ShippingAddressId INT
)
然后你必须把你的班级改为:
public class Order
{
public string OrderId { get; set; }
public int ShippingAddressId {get; set;}
public virtual Address ShippingAddress { get; set; }
public int BillingAddressId {get; set;}
public virtual Address BillingAddress { get; set; }
}
只需使用多映射。
另一种选择是使用Dapper扩展程序,例如Dapper-FluentMap或Dapper Extensions,它们可以帮助您将列映射到类。