2009-06-03 155 views
9

假设以下层次:实体框架:继承与包括

class Department { EntityCollection<Employee> Employees; } 

class Employee { string Name; } 

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

所以,部门包含员工的列表。有员工类型的层次结构,某些类型引用其他实体。 假设我们需要将员工加载到部门。好的,不是问题:

dataContext.Departments.Include("Employees") 

这将返回具体的员工类型(即远程员工的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 

我应该在Include中指定要使用RemoteEmployee加载位置的内容吗?

+1

ALex的解决方案出了什么问题。你为什么不接受它,以便从中得到回报? – VdesmedT 2011-06-04 05:14:47

回答

13

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

我不认为你可以使用包含做到这一点,但你可以使用投影招看到这个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); 
} 

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

希望这会有帮助 Alex

+1

谢谢,这有帮助。我不能说我对这个解决方案很满意。 现在我只需手动加载所需的属性: department.Employees.OfType .ForEach(re => re.LocationReference.Load()); 它似乎更可读,但速度成本。 – 2009-06-09 09:25:39