PagedList与实体框架获取所有记录 [英] PagedList with Entity Framework getting all records

查看:288
本文介绍了PagedList与实体框架获取所有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pagedList是一个分页库。

  _dbContext.Products.ToList()。ToPagedList(1,25); 

上述代码将在第1页的数据库中获得前25条记录。



问题是, ToList()调用将获取数据库中的所有记录。然后, ToPageList()调用将选择前25个记录。



如何将EF与PagedList组合使用我只得到数据库中的前25条记录?并没有得到所有记录,然后取第25个记录。



PS:我应该写我自己的分页库还是使用在线图书馆?请建议我任何其他图书馆。

解决方案

确实,你正在做一个 ToList(),所以查询将被执行,延期执行将不会被推迟。



你可以试试没有 ToList ()调用,但这一切都取决于 ToPagedList(int,int)方法的实现。



你可以自己做分页。

  int pageSize = 25; 
int pageNumber = 1;

IQueryable< Product> query = _dbContext.Products;
var pagedQuery = query.Skip(pageSize *(pageNumber - 1))。Take(pageSize).Tolist();是的,你可以把这个逻辑隐藏在 IQueryable< code code code code $ ; T>

  public static class IQueryableExtensions {
public static IQueryable< T> ToPagedQuery< T>(this IQueryable< T>查询,int pageSize,int pageNumber){
return query.Skip(pageSize *(pageNumber - 1))。
}
}


PagedList is an Paging library.

_dbContext.Products.ToList().ToPagedList(1, 25);

Above code will get first 25 record in database for Page 1.

The problem is that the ToList() call will get all record in the database. Then the ToPageList() call will select the first 25 records.

How do I combine EF with PagedList so that I only get the first 25 records in the database? And not get all records, and then take the first 25 record.

PS: Should I write my own Paging library or use an online library? Please suggest me any other library.

解决方案

Indeed, you are doing a ToList(), so the query will be executed, and deferred execution won't be deferred anymore.

You can try it without the ToList() call, but it all depends on the implementation of the ToPagedList(int, int) method.

You can just do the paging yourself.

int pageSize = 25;
int pageNumber = 1;

IQueryable<Product> query = _dbContext.Products;
var pagedQuery = query.Skip(pageSize * (pageNumber - 1)).Take(pageSize).Tolist();

And yes, you can just hide this logic behind an extension method on IQueryable<T>.

public static class IQueryableExtensions {
    public static IQueryable<T> ToPagedQuery<T>(this IQueryable<T> query, int pageSize, int pageNumber) {
        return query.Skip(pageSize * (pageNumber - 1)).Take(pageSize);
    }
}

这篇关于PagedList与实体框架获取所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆