[英]Dapper map with prefix in column name
I have 2 classes, Order and Address as following:我有 2 个类,顺序和地址如下:
public class Order
{
public string OrderId { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
}
and和
public class Address
{
public string Street { get; set; }
public string Town { get; set; }
public string Zip { get; set; }
}
The database stores the orders and address in a single table like this:数据库将订单和地址存储在一个表中,如下所示:
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)
)
How can i get dapper to map this to the Order class?我怎样才能让 dapper 将它映射到 Order 类?
Here's how you can do that by making the query generalize the billing and shipping columns and using the version of Query
that takes multiple types and telling it to split when it sees a column called "Address".您可以通过以下方式实现这一点:使查询概括计费和运输列,并使用具有多种类型的
Query
版本,并在它看到名为“地址”的列时告诉它进行拆分。 Then you just assign the Address
objects to the appropriate property on the Order
object.然后,您只需将
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");
I don't think it is possible with Dapper since it treats row as a single object.我认为 Dapper 不可能,因为它将行视为单个对象。 It would be possible if you would change your table structure:
如果您更改表结构,则有可能:
CREATE TABLE Orders
(
OrderId NVARCHAR(56) PRIMARY KEY,
BillingAddressId INT
ShippingAddressId INT
)
Then you would have to change your class to:然后,您必须将类更改为:
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; }
}
And just use multi mapping.只需使用多映射。
Another option is to use Dapper extensions like Dapper-FluentMap or Dapper Extensions which will help you map columns to classes.另一种选择是使用 Dapper -FluentMap或Dapper Extensions等Dapper 扩展,这将帮助您将列映射到类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.