Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper multiple objects from one row

Tags:

c#

dapper

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?

  • I know I can do this by returning a dynamic and mapping each object manually, which is painful as in my scenario we have a large number of columns. I'd rather not do this. (And no, it can't be redesigned to require less columns.)

What I've tried:

  • I've looked into QueryMultiple<Person,Pet>, but it assumes I am running multiple queries. In my real-life scenario, this is a very expensive query, and I'd like to just run it once.
  • I've also looked into returning Query<Person,Pet,Tuple<Person,Pet>>, but this requires an Id column, here there's no hierearchical relationship or Ids. I just want to take a single row and map it to multiple columns.
like image 404
Jay Sullivan Avatar asked Jul 19 '13 20:07

Jay Sullivan


People also ask

What is splitOn in dapper?

splitOn: CustomerId will result in a null customer name. If you specify CustomerId,CustomerName as split points, dapper assumes you are trying to split up the result set into 3 objects. First starts at the beginning, second starts at CustomerId , third at CustomerName .

What is QueryFirstOrDefault?

Note: QueryFirstOrDefault method is a method that can execute a query and map the first result, or a default value if the sequence contains no elements.


1 Answers

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");
like image 90
Eren Ersönmez Avatar answered Sep 25 '22 16:09

Eren Ersönmez