https://github.com/TroyGoode/PagedList
具有这种用法示例MyProductDataSource.FindAllProducts的
var products = MyProductDataSource.FindAllProducts(); //returns IQueryable<Product> representing an unknown number of products. a thousand maybe?
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfProducts = products.ToPagedList(pageNumber, 25); // will only contain 25 products max because of the pageSize
典型implmentations尝试PagedList.Mvc库( );沿的
public IQuerable<T> MyProductDataSource.FindAllProducts()
{
using (var ctx = new MyCtx())
{
return ctx.MyList().Where(....);
}
}
其中当然也有出现InvalidOperationException()和的DbContext已经配置消息
寻找如何返回的IQueryable可以在这里使用没有问题的最佳实践行?
这不是一个典型的实现。通常情况下,您将一个上下文注入到存储库类中,这意味着您不会在方法级别进行处理。 – 2013-05-08 18:02:23
@WiktorZychla我不同意。两者都是有用的实现。如果可以将上下文范围本地化为方法,这是可以接受的事情,但是当查询的生成超出了该方法的范围时(这不是一个选项),在这种情况下,您需要调整上下文的范围,例如无论它在哪里,它都包含该查询的生命周期。程序员应该能够理解任何给定查询的生命周期,并确定上下文的范围,使其处于同一“级别”,不多也不少。 – Servy 2013-05-08 18:04:52
@Servy:true,但在大多数情况下,您的上下文生存期是“per-http-context”。请注意,他用asp.net标记问题。你所说的是一个普遍的理论,他需要一个精确的指导,为他的具体,asp.net场景。 – 2013-05-08 18:07:52