9

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

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This didn't work for me. I had to swap the position of Name: .Query<Person, Name, Person>(..., (person, name) => ... ). Also, splitOn: "Age" isn't working for me either - I keep getting this error: "When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id"
I misunderstood what splitOn was actually doing... that part is working fine... but I still needed to swap Name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.