I'm having a problem with Dapper when I do not expose my foreign keys and child collections in the POCO model. Let's take a simple example with the two entities:
Bike (Id, ModelName)
Tire (Id, Tread)
In the database each Tire has a foreign key to Bike. But my model does not.
From the database, I want to materialize this structure into a Dictionary<Bike, IEnumerable<Tire>>
. Where each Bike (unique) will have two tires.
I could select this one-to-many relationship using the following query:
SELECT b.Id, b.ModelName, t.Id, t.Tread
FROM Bike b
JOIN Tire t ON b.Id = t.bike_id
In order to map that using Dapper, I have done the following:
var dbResult = connection.Query<Bike, Tire, KeyValuePair<Bike, Tire>>("sql-query-above",
(a, s) => new KeyValuePair<Bike, Tire>(a, s);
splitOn: "Id");
And to turn that result into my dictionary, using LINQ:
Dictionary<Bike, IEnumerable<Tire>> dict = dbResult.GroupBy(g => g.Key, g => g.Value).ToDictionary(g => g.Key, g => g.AsEnumerable());
And it correctly returns the data structure:
Bike #1
- Tire #1
- Tire #2
Bike #2
- Tire #3
- Tire #4
But is this the most efficient way of materializing this data structure? An alternative would be to avoid the dictionary and create other entities that exposes the foreign keys and relationships (e.g. Tires collection on Bike and FK on Tire), and use a mapping approach like described here. But I would like to avoid that in my model because it would result in lots of extra classes. But what about performance? Is this worse or the same?