Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 在EF查询中包含孙辈_Entity Framework_Linq To Entities - Fatal编程技术网

Entity framework 在EF查询中包含孙辈

Entity framework 在EF查询中包含孙辈,entity-framework,linq-to-entities,Entity Framework,Linq To Entities,给定对象层次结构 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 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语法防止在随后更改类名时中断查询。但是,如果
Parent
有一个
ICollection
像这样:

public class Parent
{
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}
字符串语法是唯一的选项,或者在这种情况下是否有其他方法可以使用Lambda语法?

当然可以

var hierarchy = from p in ctx.Parents
                    .Include(p => p.Children.Select(c => c.GrandChild))
                select p;
请参阅标题备注,第五个项目符号。

更新: 如果使用的是实体框架核心,则应使用以下语法

var hierarchy = from p in ctx.Parents
                    .Include(p => p.Children)
                    .ThenInclude(c => c.GrandChild)
                select p;

注意:在我的例子中,出于某种奇怪的原因,intellisense不会在“.ThenInclude”lambda子句中提示我孙子对象,但这是一个边缘情况,intellisense是错误的,没有关系-代码仍在编译中。如果需要包含孙子(又名孙子)的子对象,该怎么办?@Julen您可以对每个嵌套的子实体使用.thenClude递归,如下所示:Parent.Include(child).thenClude(grand孙).thenClude(grand孙)。。艾彻:你会包括两个不同的孙子,比如说孙子和孙女吗?类似于
ctx.Parents.Include(p=>p.Children)。然后Include(c=>c.grands)…
。您无法添加
然后添加Include(c=>c.grand媳妇)
,因为它会在GrandSon对象中查找孙女。@SimonTewsi不幸的是,现在唯一的方法是
。第二次添加顶级,然后执行另一个
。然后对要包含的另一个子项执行include
。要像这样使用include方法,请不要忘记引用
System.Data.Entity
。如果孙子有子项,您也可以递归地为后代继续此Select()模式,以此类推。
var hierarchy = from p in ctx.Parents
                    .Include(p => p.Children.Select(c => c.GrandChild))
                select p;
var hierarchy = from p in ctx.Parents
                    .Include(p => p.Children)
                    .ThenInclude(c => c.GrandChild)
                select p;