【问题标题】:Include children and grandchildren when selecting from database从数据库中选择时包括子孙
【发布时间】:2014-01-03 14:04:51
【问题描述】:

我有以下型号

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; }
}

我现在要做的是从数据库中选择父母的列表以及孩子和孙辈。

不高兴地尝试了以下:

List<Parent> parent = new List<Parent>();
parent = db.parent.ToList();

【问题讨论】:

    标签: entity-framework linq-to-sql


    【解决方案1】:

    使用Include 方法:

    parent = db.parent.Include(parent => parent.Child.Select(child => child.GrandChild)).ToList();
    

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

    parent = db.parent.Include("Child.GrandChild").ToList();
    

    或者您可以使用我在博客中提到的here 的自定义Include 扩展方法。

    【讨论】:

    • 得到以下错误 Cannot convert lambda expression to type 'string' because it is not a delegate type
    • @Ernie,您可能使用的是旧版本的 EF。请参阅我的更新答案。
    • 一直在尝试使用 lambda 表达式,但无法弄清楚为什么它不起作用。感谢您的帮助。
    • 对于 EF Core,请考虑使用此答案中的语法 stackoverflow.com/a/38741905/1047812
    • Eager Loading 的 .Include 语法是否保证 EF 将加载关系?很高兴知道它将在什么情况下加载以及何时可能只是一个提示......我找不到任何说明任何方式的文档。
    【解决方案2】:

    在 Linq to Sql 中你应该使用DataLoadOptions

    var dlo = new DataLoadOptions();
    
    dlo.LoadWith<Parent>(p => p.Child );
    dlo.LoadWith<Child>(c=> c.GrandChild );
    db.LoadOptions = dlo;
    
    List<Parent> parent = new List<Parent>();
    parent = db.parent.ToList();
    

    【讨论】:

      猜你喜欢
      • 2014-10-08
      • 1970-01-01
      • 2013-01-25
      • 2010-12-23
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      相关资源
      最近更新 更多