Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper multi mapping two properties of the same type

Tags:

dapper

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?

like image 219
batwad Avatar asked Jun 01 '16 11:06

batwad


1 Answers

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");
}
like image 196
batwad Avatar answered Oct 24 '22 08:10

batwad