EF - 为什么不包括属性工作
所以我的课程看起来像这样。
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 执行查询时,包含有效,但是当我对成员 IList 执行 AsQueryable() 时,包含不起作用。
有没有办法在延迟加载的属性(例如上面的 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 个查询获得相同结果可能存在巨大差异。
提前致谢。
So I have classes that looks like this.
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;}
}
When I perform the query directly against the DataContext the Include works, but when I do an AsQueryable() on the IList of members the include doesn't work.
Is there a way to have Include/Eager functionality on lazy loaded properties, such as the Members property above, or do I always have to go through the DataContext to get that feature?
User.Members.AsQueryable().Include(a => a.Another).ToList() // <-- nada, no way Jose
_db.Members.Include(m => m.Another).ToList() // <-- all good in the neighborhood
I ask cause it can be a huge difference of 1 sql query vs. 100 queries for something result equivalent.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
您必须遍历 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;
}
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
AsQueryable
不会使其成为 linq-to-entities 查询。它仍然是List
之上的 Linq-to-object 查询。List
不知道如何处理Include
- 只有DbQuery
知道它,因此您必须获取DbQuery
:AsQueryable
doesn't make it linq-to-entities query. It is still Linq-to-object query on top ofList
.List
doesn't know how to handleInclude
- onlyDbQuery
knows it so you must getDbQuery
: