Jay Sullivan
Jay Sullivan

Reputation: 18249

Dapper multiple objects from one row

I have one row coming from the database

select "John" Name, 
       "Male" Gender,
       20 Age,
       "Rex" PetName,
       "Male" PetGender,
       5 PetAge
       // ... many more ...

Using Dapper, I'd like to pull this row into two objects:

class Person
{
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Age { get; set; }
    // ... many more ...
}    
class Pet
{
    public string PetName { get; set; }
    public string PetGender { get; set; }
    public int PetAge { get; set; }
    // ... many more ...
}

Note: there is no hierarchical relationship here, I'm simply trying to map one database row into two (or more) objects.

How can I do this using dapper?

What I've tried:

Upvotes: 16

Views: 12655

Answers (1)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

You were pretty close to solution with the Query method. If you don't have an Id column, then you can provide a splitOn argument:

connection.Query<Person, Pet, Tuple<Person, Pet>>(sql, 
    (person, pet) => Tuple.Create(person, pet), splitOn: "PetName");

Upvotes: 21

Related Questions