I'm trying to speed up some of my db tier functions by adding the proper Include statements to force eager loading and reduce the number of queries I make to the database.
However in 90% of the cases I run into the problem that I'm not at the correct "starting location" to enter the includes I want.
The simplest example I could come up with:
I have Department, Course and Student entities with many-to-many relationships between them (some courses below to multiple departments).
Now I have a function
GetMasterCourses(Department dep)
which does something like
return dep.Courses.Where(c => c.level == "Master")
The question is: how do I tell EF to load all students associated with each queried course?
The only solutions I have found are things like:
courseIDs = dep.Courses
.Where(c => c.level == "Master").Select(c => c.courseID)
dbcontext.Courses
.Include("Students")
.Where(c => courseIDs.Contains(c.courseID) and c.level == Master)
This seems rather silly to have to do such a workaround just to be able to specify the correct Include. I have looked at many examples of Include and searched many questions on stackoverflow but can't really find anyone with this problem, eventhough it seems a quite common problem.