Is there a way of using MultiMapping and QueryMultiple together in Dapper?

无人久伴 提交于 2019-12-10 03:05:42

问题


I have a few queries that I need to run together and I can do so using the QueryMultiple feature.

But in this case I've not been able to find out how could I use MultiMapping.

Does anyone know a way of achieving this?


回答1:


I think this is what you're looking for though it's hard to tell without an example of the query you are trying to execute.

var sql = @"Select * 
            From Parent 
            Left Join Child on Child.ParentID = Parent.ParentID 
            Where Parent.ParentID = @id
            ... more queries";

using(var reader = connection.QueryMultiple(sql, new {id=selectedId}))
{
    var stuff = reader.Read<Parent, Child, Parent>(
        (p,c)=> 
        {
            p.Child = c;
            return p;
        }, splitOn: "ChildId").Single();
    // Continue to read from the other queries in your sql.
}

Basically the Read method of the SqlMapper.GridReader is similar to the Query extension method. You only get the splitOn parameter with one of the overloads that takes more than two generic types.




回答2:


Theres a quick example taken from another thread: how-to-get-values-for-child-objects

var sql = 
@"
select * from PROFILES where profileId= @id
select * from PROFILEIMAGES where OWNER_PROFILESIDFK = @id";

using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
   var profile = multi.Read<Models.PROFILE>().Single();
   profile.ProfileImages = multi.Read<Model.PROFILEIMAGES>().ToList();
} 

Each query returns a set of objects which then can be mapped to your entities.



来源:https://stackoverflow.com/questions/10319140/is-there-a-way-of-using-multimapping-and-querymultiple-together-in-dapper

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