2011-09-12 123 views
4

所以我有类似这样的类。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 

我问原因也可以是一个SQL语句对100个查询的东西,结果相当于一个巨大的差异。

在此先感谢。

回答

3

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(); 
0

你必须要经过的DbContext,以便包括()工作。你可以将它抽象成一个Repository,但是你仍然需要将你的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; 
    } 
+0

这是一个很好的答案解决方案,刚刚结束了在我的datacontext上为常见查询场景创建专用属性。虽然也可以实施这个。 –

-1

我也面临着同样的问题。

我解决了这个刚刚将基准System.Data.Entity的&使用以下命名空间:

using System.Data.Entity; 

你可以用它试试。

相关问题