Let's say I have contacts stored in my database in a flattened form, such that I query them like this:
SELECT Name, HomeHouseNumber, HomePostcode, WorkHouseNumber, WorkPostcode FROM Contacts
I would like a little more structure in my C# code and have this simple definition of a contact with a home and work address.
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; }
}
I've found I can use multi mapping do extract the home address by aliasing the columns in the select like this:
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");
}
However I cannot alias the work address columns in such a way that they will be mapped. Can Dapper perform this mapping for me or must I do it manually?
The solution, incredibly, is to give the columns the same alias. I didn't think SQL would allow this, but it does and Dapper maps it all perfectly.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With