Search code examples
c#sqldappermulti-mapping

Dapper Multipmapping collection within collections


In Dapper, what's the best way to map and object that contains a list and each of those list items have their own lists?

class Object1 {
    int Object1Id;
    List<Object2> object2s;
}

class Object2 {
    int Object2Id;
    List<Object3> object3s;
}

class Object3 {
    int Object3Id;
}

Here's the SQL I wanted to use

SELECT *
  FROM [Object1] o1
  left join [Object2] o2 on o1.Object1Id = o2.Object1Id
  left join [Object3] o3 on o2.Object2Id = o3.Object2Id

Using the Left joins because it's possible Object1 has no Object2's and Object2's may not have any Object3's

I thought about using

connection.Query<Object1, Object2, Object3, Object1>

but keeping track of a dictionary within a dictionary to add them to the list seems like a lot of lines of code.

Would I be better off using QueryMultiple?


Solution

  • You're absolutely right : this kind of parent-child handling isn't a scenario that dapper handles very well right now. It would be nice if it did, but it simply hasn't been the top priority to do something about it.

    You have a choice of two inelegant solutions. Personally I think the QueryMultiple approach is proabbly cleaner.