Dapper Syntax for Nested Multi Mapping

.net dapper multi-mapping

Question

    class Person
    {
        Address Addr { get; set; }
        int Age { get; set; }
    }

    class Address 
    {
        string StreetName { get; set; }
        County Cnty { get; set; }
    }

    class County
    {
         string CntyName;
         string CntyCode;
    }

Here is my Stored Proc which populates the data from Database.

    Create Procedure SpGetAllPersons
    As
    Select CntyName, CntyCode, StreetName, Age from Persons

I tried to write below dapper query but getting an exception

    DBConn.Query<County, Address , Person, Person>
    (DomainConstants.SpGetAllPersons,
    (cnty, address, person) =>
    {
            address.Cnty = cnty;
            person.Addr = address;
            return person;
    },
    commandType: CommandType.StoredProcedure,
    splitOn: "StreetName, Age").ToList();

I tried to use below concept, but it returns single object only. I need a list of persons.

     var sql =
    @"select 
        1 as PersonId, 'bob' as Name, 
        2 as AddressId, 'abc street' as Name, 1 as PersonId,
        3 as Id, 'fred' as Name
        ";
                var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>>
                    (sql, (p, a, e) => Tuple.Create(p, a, e), splitOn: "AddressId,Id").First();

Thanks in advance.

Accepted Answer

Thanks Mark and Bob for jumping on it. I was able to resolve the issue other way:

    DBConn.Query(DomainConstants.SpGetAllPersons, commandType: CommandType.StoredProcedure)
    .Select(x => new Person
    {
        Addr = new Address
        {
            Cnty = new County
            {
                CntyName = x.CntyName,
                CntyCode = x.CntyCode
            },
            StreetName = x.StreetName
        },
        Age = x.Age
    }).ToList();

Expert Answer

Well, in the example you are only selecting a single row, so that won't ever return more than one. However, Query<T> returns an IQueryable<T>. You are calling .First(), so it isn't surprising that you get exactly one result. If you change the last part of your statement to use .ToList() you will get a list with one item per row.




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