Writing Dapper Query for Nested Objects

dapper orm

Question

I have a code Structure as below:

class Person
{
    Name PersonName;
    int Age;
}

class Name
{
    string FirstName { get; set; }
    string LastName { get; set; }
}

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

Create Procedure SpGetAllPersons
As
Select FirstName, LastName, Age from Persons

How do I write Dapper query which pulls all the Person from Database?

Example:

List<Person> Persons = DbConn.Query<Person>("SpGetAllPersons", CommandType.StoredProcedure);

Accepted Answer

You need to use the multi mapper if you want to select nested objects.

This should work:

List<Person> persons = DbConn.Query<Name,Person,Person>
  ("SpGetAllPersons",
     (name,person) => {person.Name = name; return person;} 
     commandType: CommandType.StoredProcedure, 
     splitOn: "Age");

The multi-mapper can return any type, even just an aggregate type that is not mapped to any db table.

It is important to supply the splitOn param if you intend to split on anything that is not called id or Id.




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