Entity Framework - Include Multiple Levels of Properties

前端 未结 8 710
囚心锁ツ
囚心锁ツ 2020-11-22 08:43

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

8条回答
  •  难免孤独
    2020-11-22 09:04

    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.

提交回复
热议问题