gpt4 book ai didi

Dapper 多映射两个相同类型的属性

转载 作者:行者123 更新时间:2023-12-04 18:03:33 29 4
gpt4 key购买 nike

假设我将联系人以扁平形式存储在我的数据库中,这样我就可以像这样查询它们:

SELECT Name, HomeHouseNumber, HomePostcode, WorkHouseNumber, WorkPostcode FROM Contacts

我想在我的 C# 代码中多一点结构,并有一个带有家庭和工作地址的联系人的简单定义。
class Address
{
public string HouseNumber { get; set; }
public string Postcode { get; set; }
}

class Contact
{
public string Name { get; set; }
public Address HomeAddress { get; set; }
public Address WorkAddress { get; set; }
}

我发现我可以使用多映射来提取家庭地址,方法是在 select 中为列设置别名,如下所示:
IEnumerable<Contact> GetContacts()
{
return Connection.Query<Contact, Address, Address, Contact>(
"SELECT Name, HomeHouseNumber as HouseNumber, HomePostcode as Postcode, WorkHouseNumber, WorkPostcode FROM Contacts",
(contact, home, work) =>
{
contact.HomeAddress = home;
contact.WorkAddress = work;
return contact;
},
splitOn: "HouseNumber,WorkHouseNumber");
}

但是,我不能以映射它们的方式为工作地址列设置别名。 Dapper 可以为我执行这个映射还是我必须手动执行?

最佳答案

令人难以置信的是,解决方案是为列提供相同的别名。我不认为 SQL 会允许这样做,但确实如此,而且 Dapper 完美地映射了这一切。

IEnumerable<Contact> GetContacts()
{
return Connection.Query<Contact, Address, Address, Contact>(
"SELECT Name, HomeHouseNumber as HouseNumber, HomePostcode as Postcode, WorkHouseNumber as HouseNumber, WorkPostcode as Postcode FROM Contacts",
(contact, home, work) =>
{
contact.HomeAddress = home;
contact.WorkAddress = work;
return contact;
},
splitOn: "HouseNumber,HouseNumber");
}

关于Dapper 多映射两个相同类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37567136/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com