Mapping multiple columns to type in Dapper

c# dapper

Question

I am trying to map select like this:

SELECT id, total, total_currency FROM sometable

id is VARCHAR, total is numeric, currency is char(3)

Into entity like this:

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

Money of course has constructor with signature (decimal amount, string currencyId). How do I achieve that in Dapper?

Popular Answer

You'll need to use multi-mapping if you have a parent/child entity relationship, re: Money is a class that is a child property of 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");

For a more detailed explanation, see: Correct use of Multimapping in Dapper

If you need custom parameters for the Money class, then it is recommended you just use the generic method and project the dynamic result into your actual result. See: Call custom constructor with Dapper?



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why