Where does paging, sorting, etc go in repository pattern?

戏子无情 提交于 2020-07-16 16:34:31

问题


Where do we put the logic for paging and sorting data in an asp.net repository pattern project?

Should it go in the service layer or put it in the controller and have the controller directly call the repository? Controller -> Repository is shown here for a jquery grid.

But unlike that article, my repository returns IQueryable<datatype>


回答1:


It should go in the Repository if your Repository returns materialized sequences (ICollection<T>, List<T>), etc.

But if your returning IQueryable<T> (like i am), i hope you have a service layer mediating between your Controllers and Repository, which executes queries on the IQueryable and materialises them into concrete collections.

So, i would put the paging in the service layer.

Something like this:

public PagedList<T> Find(Expression<Func<T,bool>> predicate, int pageNumber, pageSize)
{
   return repository
             .Find()
             .Where(predicate)
             .ToPagedList(pageNumber, pageSize);
}

.ToPagedList can be an extension method that applies the paging you require and projects to a PagedList<T>.

There are many PagedList<T> implementations out there. I like Rob Conery's one. Has properties that your View requires, so you can bind to a PagedList<T> and create a HTML Helper to render out the page numbers very easily. The only problem with any paged list LINQ implementation is the Count() operation (for the number of records) needs to be done on the server and hence results in 2 round trips.

You don't want to be returning non-materialized queries to your View's, as IMO this breaks the MVC pattern.

Each time you go to a new page, call your service to retrieve the required result.




回答2:


  • Sorting: should be done in the repository for large result sets; may be done inside the controller for small collections (i.e. without paging).
  • Paging: IMO the repository should expose a way of returning collection slices (which is not exactly the same as paging). Meaning, there should be a way of asking the repository to return a query, starting at the index z and for the next y items. Then everything related to the particular page size (or page index) should be kept inside the controller. That way you can optimize data retrieval, but without coupling your model to a particular presentation requirement.



回答3:


Sorting and paging are data functions. It should go in the repository.




回答4:


The repository should return a 'PageableResultSet', or something like that, which is responsible for the paging.




回答5:


I believe paging should go in the repository. See this answer I posted on another question.

Repositories and persistence ignorance again



来源:https://stackoverflow.com/questions/5031675/where-does-paging-sorting-etc-go-in-repository-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!