PagedList with Entity Framework receiving all records

PagedList is a swap library.

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

The above code will get the first 25 records in the database for Page 1.

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

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

PS: Do I have to write my own swap library or use the online library? Please offer me any other library.

+6
source share
2 answers

Indeed, you are doing ToList() , so the request will be executed, and delayed execution will no longer be delayed.

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

You can just do the paging yourself.

 const int pageSize = 25; const 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 the 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); } } 
+6
source

The simplest solution is to use AsEnumerable() , but this requires ordering. Unlike ToList() , AsEnumerable() does not fall into the database.

 _dbContext.Products.OrderBy(p => p.Id).AsEnumerable().ToPagedList(1, 25); 
+4
source

Source: https://habr.com/ru/post/957329/


All Articles