如何在 ASP.NET MVC 的 EF6 中包含多个导航属性的导航属性,并具有预加载?

szt*_*516 3 c# linq asp.net-mvc entity-framework-6

我一直在尝试包含以前包含的导航属性的多个导航属性,但我还没有找到正确的语法。实体关系如下图所示:

实体关系

现在,我想加载所有城市,然后是所有部门,然后是所有员工,当我来到 Employee 表时,我想加载 Employee 导航属性:Projects(项目的集合)以及导航属性 Title 和 Country .

我的代码语法是:

var model = dbContext.Cities.Include(c => c.Departments.Select(e => e.Employees.Select(p => p.Projects))).ToList();
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,唯一包含的 Employee 导航属性是 Projects(一个 Project 列表,由于是一对多的关系)。但是如何包含另外两个 Employee 导航属性 Title 和 Country?

Tie*_* T. 6

您需要或多或少地为要加载的每个导航属性重复您的 Include :

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();
Run Code Online (Sandbox Code Playgroud)

EF Core 中的语法更简单,使用.ThenInclude,但我不知道在 .NET Framework 中使用更简单的方法。

包括,只是为了让您看到它,但不适用于 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();
Run Code Online (Sandbox Code Playgroud)