Dapper multi mapping two properties of the same type

谁说我不能喝 提交于 2019-12-22 06:59:43

问题


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?


回答1:


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");
}


来源:https://stackoverflow.com/questions/37567136/dapper-multi-mapping-two-properties-of-the-same-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!