从数据库中选择时包括子代和孙代

Ern*_*nie 3 entity-framework linq-to-sql

我有以下型号

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Child> Child { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<GrandChild> GrandChild { get; set; }
}

public class GrandChild
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我现在想做的是从数据库中选择一个包含孩子和孙子的父母列表。

尝试了以下方法,但没有感到高兴:

List<Parent> parent = new List<Parent>();
parent = db.parent.ToList();
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 5

使用Include方法:

parent = db.parent.Include(parent => parent.Child.Select(child => child.GrandChild)).ToList();
Run Code Online (Sandbox Code Playgroud)

对于旧版本的实体框架,您必须使用字符串而不是 lambda 表达式:

parent = db.parent.Include("Child.GrandChild").ToList();
Run Code Online (Sandbox Code Playgroud)

或者您可以使用我在此处Include发布的博客中介绍的自定义扩展方法。