2009-06-03 131 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