The Include() method works quite well for Lists on objects. But what if I need to go two levels deep? For example, the method below will return ApplicationServers with the i
More EFCore examples on MSDN show that you can do some quite complex things with Include
and ThenInclude
.
This is a good example of how complex you can get (this is all one statement!):
viewModel.Instructors = await _context.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.CourseAssignments)
.ThenInclude(i => i.Course)
.ThenInclude(i => i.Enrollments)
.ThenInclude(i => i.Student)
.Include(i => i.CourseAssignments)
.ThenInclude(i => i.Course)
.ThenInclude(i => i.Department)
.AsNoTracking()
.OrderBy(i => i.LastName)
.ToListAsync();
See how you can chain Include
even after ThenInclude
and it kind of 'resets' you back to the level of the top level entity (Instructors).
You can even repeat the same 'first level' collection (CourseAssignments) multiple times followed by separate ThenIncludes
commands to get to different child entities.
Note your actual query must be tagged onto the end of the Include
or ThenIncludes
chain. The following does NOT work:
var query = _context.Instructors.AsQueryable();
query.Include(i => i.OfficeAssignment);
var first10Instructors = query.Take(10).ToArray();
Would strongly recommend you set up logging and make sure your queries aren't out of control if you're including more than one or two things. It's important to see how it actually works - and you'll notice each separate 'include' is typically a new query to avoid massive joins returning redundant data.
AsNoTracking
can greatly speed things up if you're not intending on actually editing the entities and resaving.