【问题标题】:EF - Why doesn't Include work on PropertiesEF - 为什么不包括属性工作
【发布时间】:2011-09-12 16:54:17
【问题描述】:

所以我的课程看起来像这样。

public class User {
    public virtual IList<Member> Members {get;set;}
}

public class Member {
    public virtual AnotherTable Another {get;set;}
}

public class AnotherTable {
    public string Name {get;set;}
}

当我直接对 DataContext 执行查询时,Include 工作,但是当我对成员的 IList 执行 AsQueryable() 时,include 不起作用。

有没有办法在延迟加载的属性(例如上面的 Members 属性)上提供 Include/Eager 功能,还是我总是必须通过 DataContext 才能获得该功能?

User.Members.AsQueryable().Include(a => a.Another).ToList() // <-- nada, no way Jose
_db.Members.Include(m => m.Another).ToList() // <-- all good in the neighborhood

我问是因为 1 条 sql 查询与 100 条查询的结果相当。

提前致谢。

【问题讨论】:

    标签: entity-framework c#-4.0 orm entity-framework-4.1


    【解决方案1】:

    AsQueryable 不会使其成为 linq-to-entities 查询。它仍然是在List 之上的 Linq-to-object 查询。 List 不知道如何处理 Include - 只有 DbQuery 知道,所以你必须得到 DbQuery

    var entry = context.Entry(user);
    entry.Collection(u => u.Member).Query().Include(m => m.Another).Load();
    

    【讨论】:

      【解决方案2】:

      您必须通过 DbContext 才能使 Include() 工作。您可以将其抽象为存储库,但您仍需要将 Include() 表达式传递给底层上下文。

          private IQueryable<T> GetQuery<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
          {
              IQueryable<T> query = _db.Set<T>();
      
              if (includeProperties != null)
              {
                  foreach (Expression<Func<T, object>> expression in includeProperties)
                  {
                      query = query.Include(expression);
                  }
              }
      
              return query;
          }
      

      【讨论】:

      • 这是一个很好的解决方案,只是最终在我的数据上下文上为常见的查询场景创建了专门的属性。不过也可以实现这一点。
      【解决方案3】:

      我也遇到了同样的问题。

      我解决了这个问题,只需添加参考 System.Data.Entity 并使用以下命名空间:

         using System.Data.Entity;
      

      你可以试试看。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        • 2013-03-11
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        • 2020-12-12
        相关资源
        最近更新 更多