我有以下型号
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; }
}
我现在要做的是从数据库中选择一个包含 child 和孙子的 parent 列表。
没有高兴地尝试了以下内容:
List<Parent> parent = new List<Parent>();
parent = db.parent.ToList();
最佳答案
使用Include
方法:
parent = db.parent.Include(parent => parent.Child.Select(child => child.GrandChild)).ToList();
对于旧版本的 Entity Framework,您必须使用字符串而不是 lambda 表达式:
parent = db.parent.Include("Child.GrandChild").ToList();
或者您可以使用我在博客中关于 here 的自定义 Include
扩展方法.
关于entity-framework - 从数据库中选择时包括子孙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20905441/