让我说我的联系人以平展的形式存储了联系人,这样我就可以这样查询:
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可以为我执行此映射,还是必须手动执行此操作?
答案 0 :(得分:7)
令人难以置信的是,解决方案是为列提供相同的别名。我不认为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");
}