9

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?

Carlos Mendes
  • 1,900
  • 1
  • 18
  • 33

2 Answers2

15

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.

Rose
  • 43
  • 6
juharr
  • 31,741
  • 4
  • 58
  • 93
1

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.

Community
  • 1
  • 1
Alex
  • 7,901
  • 1
  • 41
  • 56
  • Thank you Alex. But I'm looking for a way of using the [Multimapping](https://github.com/SamSaffron/dapper-dot-net/blob/master/Tests/Tests.cs#L459) feature – Carlos Mendes Apr 27 '12 at 12:57
  • Could you provide an example on what you're trying to do? – Alex Apr 27 '12 at 13:24
  • 1
    Basically I store some fields denormalized in SQL (eg: a DTags field where I have all the tags separated by ";", etc). And when I use the QueryMultiple (Read method) there's no option to use the "split" parameter as in the MultiMapping queries – Carlos Mendes Apr 28 '12 at 16:20
  • What if you need to return a list of profiles? Single() won't return as List. – johnny Jan 30 '17 at 16:23
  • @johnny See juharr's example with multi mapping. – Alex Jan 30 '17 at 16:36