Search code examples
.netsqldapper

Dapper Multi Mapping with QueryMultiple


I have a stored procedure that returns multiple result sets. I'm executing this with dapper.

One of the result sets is Person JOIN Checks, where Person can have many Checks.

The end goal is to have distinct person objects that have a collection of check objects.

QueryMultiple gives me a Sqlmapper.GridReader. I see an overload of SqlMapper.GridReader.Read() that takes a Func<TFirst, TSecond, TReturn>.

Is there an example of how to use this?


Solution

  • Here's how I got it working:

    var q = _sqlConnection.QueryMultiple("MySproc",
                                         myParams,
                                         commandType: CommandType.StoredProcedure);
    var set1 = q.Read<Set1Type>();
    
    var set2Func = new Func<Person, Check, Person>((p, c) => {
        p.CheckAlert = c;
        return p;
    });
    
    var set2 = q.Read(set2Func, "CheckId")
                .GroupBy(x => x.PersonId)
                .Select(x => {
                    var person = x.First();
                    person.Checks = x.Select(p => p.Check).ToArray();
                    person.Check = null; // i really don't like this
                    return person;
                })
                .ToArray();
    

    As the comment says, I don't like the unneeded check property on the Person object.

    I'd still love to hear of a better way of doing this.