I'm currently using Entity Framework for my db access but want to have a look at Dapper. I have classes like this:
public class Course{
public string Title{get;set;}
public IList<Location> Locations {get;set;}
...
}
public class Location{
public string Name {get;set;}
...
}
So one course can be taught at several locations. Entity Framework does the mapping for me so my Course object is populated with a list of locations. How would I go about this with Dapper, is it even possible or do I have to do it in several query steps?
Dapper is not a full blown ORM it does not handle magic generation of queries and such.
For your particular example the following would probably work:
Grab the courses:
Grab the relevant mapping:
Grab the relevant locations
Map it all up
Leaving this to the reader, you create a few maps and iterate through your courses populating with the locations.
Caveat the
in
trick will work if you have less than 2100 lookups (Sql Server), if you have more you probably want to amend the query toselect * from CourseLocations where CourseId in (select Id from Courses ... )
if that is the case you may as well yank all the results in one go usingQueryMultiple
Sorry to be late to the party (like always). For me it's easier to use a Dictionary like @Jeroen-k did, in terms of performance and readability, also to avoid header multiplication across "locations", I use Distinct to remove potential dups:
Something is missing. If you not specify each field from Locations in the SQL query, the object Location cannot be filled. Take a look:
Using "l.*" on query, I had the list of locations but without data.
Not sure if anybody needs it but I have dynamic version of it without Model for quick & flexible coding.
Alternatively, you can use one query with a lookup:
See here https://www.tritac.com/blog/dappernet-by-example/
No need for
lookup
Dictionary