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>
The sorting mechanism places the resources in order; the pagination mechanism then returns a specific range of those ordered resources. You control sorting and pagination through URL query parameters.
Overview. The Repository-Service pattern breaks up the business layer of the app into two distinct layers. The lower layer is the Repositories. These classes handle getting data into and out of our data store, with the important caveat that each Repository only works against a single Model class.
The idea behind the Repository pattern is to decouple the data access layer from the business access layer of the application so that the operations (such as adding, updating, deleting, and selecting items from the collection) is done through straightforward methods without dealing with database concerns such as ...
Offset pagination is one of the simplest to implement. It's achieved using the limit and offset commands. Offset pagination is popular with apps powered by SQL databases, as limit and offset are already included with the SQL SELECT library.
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.
Sorting and paging are data functions. It should go in the repository.
The repository should return a 'PageableResultSet', or something like that, which is responsible for the paging.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With