.netdappermulti-mapping

Dapper Syntax for Nested Multi Mapping


    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.


Solution

  • 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();