【问题标题】:How can I get an IList of entites and their child objects in Entity Framework efficiently?如何有效地获取实体框架中的实体及其子对象的列表?
【发布时间】:2010-10-17 19:22:11
【问题描述】:

也就是说,我想这样做:

var lists = (from list in this.DB.Lists
             select new
             {
                 List = list,
                 Items = list.ListItems.ToList(),
             }).ToList();

但是,很明显,Entity Framework 不支持 select 子句中的 ToList 扩展方法。

我该怎么办?我尝试过的任何其他方法最终都会在迭代时向数据库发送大量查询。

【问题讨论】:

    标签: .net entity-framework iqueryable


    【解决方案1】:

    你试过Includeetension方法吗?

    var lists = (from list in this.DB.Lists.Include("ListItems")
                 select list).ToList(); 
    
    foreach(var item in lists)
    {
       // there shouldn't be any DB calls here.
       var items = list.ListItems.ToList();
    }
    

    【讨论】:

    • @John Gietzen,我知道,这很糟糕...但是您可以使用 lambda 表达式,详情请参阅 this article
    【解决方案2】:

    您不能在被转换为 SQL 的查询部分调用 ToList,但您可以在本地使用 AsEnumerable

    var lists = (from list in this.DB.Lists.AsEnumerable()
                 select new
                 {
                     List = list,
                     Items = list.ListItemsItems.ToList()
                 }).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      相关资源
      最近更新 更多