[英]Include Grandchildren in EF Query
給定對象層次結構
public class Parent
{
public int Id { get; set; }
public virtual Child Child { get; set; }
}
public class Child
{
public int Id { get; set; }
public virtual GrandChild GrandChild { get; set; }
}
public class GrandChild
{
public int Id { get; set; }
}
和數據庫上下文
public class MyContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
}
可以使用 Lambda 語法( using System.Data.Entity
)包括子孫后代,如下所示:
using (MyContext ctx = new MyContext())
{
var hierarchy =
from p in ctx.Parents.Include(p => p.Child.GrandChild) select p;
}
如果類名隨后被更改,Lambda 語法可防止中斷查詢。 但是,如果Parent
有一個像這樣的ICollection<Child>
:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
Lambda 語法不再有效。 相反,可以使用字符串語法:
var hierarchy = from p in ctx.Parents.Include("Children.GrandChild") select p;
字符串語法是唯一的選擇,還是在這種情況下有其他方法可以使用 Lambda 語法?
當然,你可以
var hierarchy = from p in ctx.Parents
.Include(p => p.Children.Select(c => c.GrandChild))
select p;
參見MSDN ,標題備注,第五個項目符號。
更新:如果您使用Entity Framework Core ,則應使用以下語法
var hierarchy = from p in ctx.Parents
.Include(p => p.Children)
.ThenInclude(c => c.GrandChild)
select p;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.