【问题标题】:Entity Framework: Inheritance and Include实体框架:继承和包含
【发布时间】:2009-06-03 11:59:24
【问题描述】:

假设以下层次结构:

class Department { EntityCollection<Employee> Employees; }

class Employee { string Name; }

class RemoteEmployee : Employee { Country Location; EntityReference<Country> CountryReference; }

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

dataContext.Departments.Include("Employees")

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

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

我应该在 Include 中指定什么来使用 RemoteEmployee 加载 Location?

【问题讨论】:

  • ALex 的解决方案有什么问题。你为什么不接受它,这样他就可以从中获得奖励?

标签: entity-framework inheritance include


【解决方案1】:

我很确定 CatZ 的建议行不通。

我认为你不能使用 Include 来做到这一点,但你可以使用投影技巧来实现相同的效果,请参阅 How to Sort Relationships in the Entity Framework

你需要做的是这样的:

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);
}

请注意,您不需要使用匿名类型来获取数据,因为实体框架的一项名为 fixup 的功能,本质上进行投影具有填充您部门的集合的副作用。

希望这会有所帮助 亚历克斯

【讨论】:

  • 谢谢,这有帮助。我不能说我对这个解决方案很满意。现在我只需使用以下方法手动加载所需的属性: department.Employees.OfType.ForEach(re => re.LocationReference.Load());它似乎更具可读性,但以速度为代价。
  • 我正在尝试实现上述解决方案,但在上面的示例中,您有d.Employees.Select(,由于多重性,我的导航属性不是一个集合,因此它没有 Select( 方法。如果它是像 d.Employee 这样的单个员工,我想检查一下 Employee 是否是某个派生类型,如果是,则加载它的导航属性。
猜你喜欢
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2011-05-19
  • 2010-10-07
  • 1970-01-01
  • 2016-06-02
相关资源
最近更新 更多