【发布时间】:2013-12-03 03:12:17
【问题描述】:
我正在使用实体框架 - 代码优先,我有下一个上下文(至少是提取):
public class TestContext : DbContext
{
public DbSet<User> Users { get; set}
public DbSet<Book> Books { get; set}
}
在用户的类中我有这个导航属性:
public virtual Collection<Book> Books { get; set}
ergo,一个用户有很多书。 问题是我想过滤书籍,但由于我的数据库中有 500.000 本书,我无法将所有书籍都放入内存并稍后过滤它们。我需要使用过滤语句对数据库执行查询。
当我这样做时:
// Doesn't matter how i get the user...
var allBooks = user.Books; // Here it brings all the books of the user
var activeBooks = allBooks.Where(n => n.Active);
我认为您可以看到问题...我想在执行之前将过滤器添加到查询中...但我不知道该怎么做。
我也将不胜感激。
谢谢。
编辑:
另一个具有显式上下文的示例,可能是清楚的事情......
IQueryable<Course> query = new TestContext().Set<User>(); // It doesn't run the query yet.
var a = query.Where(n => n.Active); // Here it runs the query!
var b = a.ToList(); // The items was on memory...
【问题讨论】:
标签: .net entity-framework ef-code-first