Dapper多重映射相同类型的两个属性 [英] Dapper multi mapping two properties of the same type

查看:87
本文介绍了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

我想在C#中增加一些结构

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

但是我不能以这样的方式为工作地址列添加别名映射。 Dapper可以为我执行此映射,还是必须手动执行?

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?

推荐答案

解决方案,令人难以置信的是,将列设置为相同的别名。我不认为SQL会允许这样做,但是Dapper可以完美地映射所有内容。

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

这篇关于Dapper多重映射相同类型的两个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆