映射多个列以在Dapper中键入

时间:2014-12-21 13:20:41

标签: c# dapper

我正在尝试映射这样的选择:

SELECT id, total, total_currency FROM sometable

id是VARCHAR,total是数字,货币是char(3)

进入这样的实体:

class MyEntity
{
     string Id { get; set; }
     Money total { get; set; }
}

Money当然有带签名(decimal amount, string currencyId)的构造函数。我如何在Dapper中实现这一目标?

1 个答案:

答案 0 :(得分:2)

如果您有父/子实体关系,则需要使用多映射,re:Money是一个属于MyEntity的子属性的类:

// assumes connection has already been created

string sql = "SELECT id, total, total_currency FROM sometable";

IEnumerable<MyEntity> result = conn.Query<MyEntity, Money, MyEntity>(
    sql,
    (entity, money) => { entity.Money = money; return entity; },
    spliton: "total");

有关更详细的说明,请参阅:Correct use of Multimapping in Dapper

如果您需要Money类的自定义参数,建议您只使用泛型方法并将动态结果投影到实际结果中。请参阅:Call custom constructor with Dapper?