Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Dapper Query for Nested Objects

Tags:

orm

dapper

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

like image 748
Rakshit Bakshi Avatar asked May 26 '11 01:05

Rakshit Bakshi


1 Answers

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.

like image 101
Sam Saffron Avatar answered Nov 19 '22 04:11

Sam Saffron