Multi mapping query with Dapper

孤街醉人 提交于 2019-12-06 21:46:33

This is an example I have found somewhere on the Dapper related sites. The point here is to have a dictionary where you keep the Entity.ID as key and Entity as dictionary value. Then in the lambda expression you check if the dictionary already contains the Entity, if yes just add the EntityIdentifier to the Entity list otherwise add the Entity returned by Dapper to the Dictionary

string cmdText = @"SELECT e.*, i.*
                   FROM Entity e INNER JOIN Identifier i ON i.EntityId = e.Id";
var lookup = new Dictionary<int, Entity>();
using (IDbConnection connection = OpenConnection())
{
    var multi = connection.Query<Entity, EntityIdentifier, Entity>(cmdText, 
                                (entity, identifier) =>
    {
        Entity current;
        if (!lookup.TryGetValue(entity.ID, out current))
        {
            lookup.Add(entity.ID, current = entity);
            current.Identifiers = new List<EntityIdentifier>();
        }
        current.Identifiers.Add(identifier);
        return current;
    }, splitOn: "i.ID").Distinct();
    return multi;
}

Sometime this becomes complicated by the parameter splitOn. Not sure if you need to repeat it adding explicitly to the Select statement (I usually use the IDTable pattern)

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