![](/img/trans.png)
[英]How to load nested entities without lazy loading in Entity Framework?
[英]Loading Nested Entities / Collections with Entity Framework
我試圖在一次調用中急切地加載所有相關實體或實體集合。 我的實體看起來像:
Class Person
{
public virtual long Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
Class Employee
{
public virtual long Id { get; set; }
public DateTime AppointmentDate { get; set; }
public virtual ICollection<EmployeeTitle> Titles { get; set; }
public virtual Person Person { get; set; }
}
Class EmployeeTitle
{
public virtual long Id { get; set; }
public virtual bool IsCurrent { get; set; }
public virtual Title Title { get; set; }
}
Class Title
{
public virtual long Id { get; set; }
public virtual string Code { get; set; }
public virtual string Description { get; set; }
}
我想要做的是,如果我調用一個方法加載所有Employees,結果應該包括Person,EmployeeTitles列表,包括Title的代碼和描述我已經能夠到達第三級,即獲得員工和人員列表EmployeeTitle。 我不知道如何使用EmployeeTitle獲取標題信息。 我的代碼是:
Context.Employees.Include("Person").Include(e => e.Titles).ToList();
請詳細說明如何實現這一目標。 提前致謝。
你可以試試這個:
Context.Employees
.Include(e => e.Person)
.Include(e => e.Titles.Select(t => t.Title))
.ToList();
Select
可以應用於集合並加載對象圖中下一級別的導航屬性。
由於這是我在谷歌搜索的第一頁,我只想發布此內容。
Slauma的答案很好。 但如果您不打算實際使用該列表,建議使用Load()而不是ToList()。 所以它會是:
Context.Employees
.Include(e => e.Person)
.Include(e => e.Titles.Select(t => t.Title))
.Load();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.