实体框架:继承和包含

Rus*_*ian 10 inheritance entity-framework include

假设以下层次结构:

class Department { EntityCollection<Employee> Employees; }

class Employee { string Name; }

class RemoteEmployee : Employee { Country Location; EntityReference<Country> CountryReference; }
Run Code Online (Sandbox Code Playgroud)

因此,部门包含员工列表.员工类型的层次结构,某些类型引用其他实体.我们假设我们需要向员工加载部门.好的,不是问题:

dataContext.Departments.Include("Employees")
Run Code Online (Sandbox Code Playgroud)

这将返回具体的员工类型(即远程员工的RemoteEmployee).现在我们需要使用远程员工加载位置.

dataContext.Departments.Include("Employees").Include("Employees.Location") - Error: no such property in Employee
dataContext.Departments.Include("Employees").Include("RemoteEmployees.Location") - Error: no such property in Department
Run Code Online (Sandbox Code Playgroud)

我应该在Include中使用RemoteEmployee加载位置?

Ale*_*mes 13

我很确定CatZ建议不起作用.

我不认为你可以使用Include来做到这一点,但你可以使用投影技巧达到同样的效果,请参阅如何在实体框架中对关系进行排序

你需要做的是这样的事情:

var results = from d in ctx.Departments
              select new {
                   d, 
                   employees = d.Employees.Select(
                      e => new {
                          e, 
                          location = e is RemoteEmployee ? 
                                     (e as RemoteEmployee).Location : 
                                     null
                     }
                   )
              };


foreach (var result in results)
{
    var re = result.d.Employees.First() as RemoteEmployee;
    Console.WriteLine("{0} {1} works from {2}", 
           re.Firstname, re.Surname, re.Location.Name);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要使用匿名类型来获取数据,实际上,由于Entity Framework的一个名为fixup的功能,执行投影会产生填充部门集合的副作用.

希望这有助于Alex