How to include multiple navigation properties of navigation property in EF6 in ASP.NET MVC with eager loading?

Viewed 3086

I have been trying to include multiple navigation properties of previously included navigation property, but I have not found correct syntax for it yet. Entity relations are shown in the picture below:

entity relations

Now, I want to load all the Cities, then all the Departments, then all the Employees and when I come to the Employee table I want to load Employee navigation properties: Projects (a collection of Project) as well as navigation properties Title and Country.

My code syntax is:

var model = dbContext.Cities.Include(c => c.Departments.Select(e => e.Employees.Select(p => p.Projects))).ToList();

In the code above the only Employee navigation property that is included is Projects (a list of Project, due to relation one to many). But how to include two other Employee navigation properties Title and Country?

1 Answers

You would need to more or less repeat your Include for each navigation property which you want loaded:

var model = dbContext.Cities
    .Include(c => c.Departments) /* loads Departments */
    .Include(c => c.Departments.Select(e => e.Employees)) /* loads Employees */     
    .Include(c => c.Departments.Select(e => e.Employees.Select(t => t.Title))) /* loads Title */
    .Include(c => c.Departments.Select(e => e.Employees.Select(t => t.Country))) /* loads Country */
    .Include(c => c.Departments.Select(e => e.Employees.Select(p => p.Projects))) /* loads Projects */
    .ToList();

The syntax is a bit simpler in EF Core, using .ThenInclude, but I'm not aware of a simpler way to do this in .NET Framework.

Including, just so you've seen it, but won't work for EF6:

var model = dbContext.Cities
    .Include(c => c.Departments)
        .ThenInclude(c => c.Employees)
            .ThenInclude(c => c.Title)
    .Include(c => c.Departments)
        .ThenInclude(c => c.Employees)
            .ThenInclude(c => c.Country)
    .Include(c => c.Departments)
        .ThenInclude(c => c.Employees)
            .ThenInclude(c => c.Projects)
    .ToList();
Related