如何返回IQueryable <T>以进一步查询

Kum*_*mar 5 .net c# asp.net-mvc visual-studio asp.net-mvc-4

我正在尝试从这里的PagedList.Mvc库

https://github.com/TroyGoode/PagedList

哪个有这个用法样本

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
Run Code Online (Sandbox Code Playgroud)

MyProductDataSource.FindAllProducts()的典型意义; 是沿着的

public IQuerable<T> MyProductDataSource.FindAllProducts()
{
   using ( var ctx = new MyCtx() )
   {
       return ctx.MyList().Where( .... );
   }
}
Run Code Online (Sandbox Code Playgroud)

当然有InvalidOperationException()和DBContext已经处理过消息

寻找有关如何返回IQueryable的最佳实践,可以在这里使用而没有问题?

Ser*_*rvy 3

您需要“向上移动”数据上下文的范围:

public IQueryable<T> MyProductDataSource.FindAllProducts(MyCtx context)
{
    return context.MyList().Where( .... );
}
Run Code Online (Sandbox Code Playgroud)

然后在更大的范围内创建上下文:

using (var ctx = new MyCtx())
{
    var products = MyProductDataSource.FindAllProducts(ctx);

    var pageNumber = page ?? 1;
    var onePageOfProducts = products.ToPagedList(pageNumber, 25);
}
Run Code Online (Sandbox Code Playgroud)