A Re-Usable NHibernate Paging Extension Method
Every developer knows that they should always try to avoid returning an unbounded result set from the database, right? Of course they do. The obvious solution to this problem is to page through the results in smaller chunks that the database (and most likely the end-user) can handle efficiently. I didn’t want to have to reinvent the wheel for every query I wrote so I wrapped the necessary NHibernate logic up in a nice, tidy extension method.
Side note: NHibernate Profiler is an indispensible tool for optimizing your NHibernate code. I couldn’t live without it, nor would I want to. And no I don’t receive kickbacks from Ayende.
Of course, in order to make this truly useful, I needed a custom collection that could keep track of the various paging settings like the current page index, the total number of records in the database, how many records are returned for each page, etc. For this, I blatantly stole borrowed the PagedList<T> code from Rob Conery and ScottGu. I also later found a great project on github by Troy Goode that is basically the same but with some supporting unit tests and optimizations. Either way, here is teh codez that I use.
PagedList.cs – contains an interface and a default implementation of a generic PagedList<T>. It also has a helper extension method so you can quickly turn any IEnumberable<T> into a PagedList<T>.
PagedList.cs
- public interface IPagedList
- {
- long TotalCount { get; set; }
- int TotalPages { get; set; }
- int PageIndex { get; set; }
- int PageSize { get; set; }
- int FirstItem { get; }
- int LastItem { get; }
- bool HasPreviousPage { get; }
- bool HasNextPage { get; }
- }
- [Serializable]
- public class PagedList<T> : IPagedList
- {
- public List<T> Items { get; private set; }
- public int TotalPages { get; set; }
- public long TotalCount { get; set; }
- public int PageIndex { get; set; }
- public int PageSize { get; set; }
- public PagedList()
- {
- Items = new List<T>();
- }
- public PagedList(IEnumerable<T> source, long totalCount, int pageIndex, int pageSize)
- {
- PageSize = pageSize;
- PageIndex = pageIndex;
- TotalCount = totalCount;
- TotalPages = (int)(TotalCount / pageSize);
- if (TotalCount % pageSize > 0)
- TotalPages++;
- Items = new List<T>(source);
- }
- public bool HasPreviousPage
- {
- get { return (PageIndex > 0); }
- }
- public bool HasNextPage
- {
- get { return PageIndex < TotalPages - 1; }
- }
- public int FirstItem
- {
- get
- {
- return (PageIndex * PageSize) + 1;
- }
- }
- public int LastItem
- {
- get { return FirstItem + PageSize - 1; }
- }
- }
- public static class Pagination
- {
- public static PagedList<T> ToPagedList<T>(this IEnumerable<T> source, int totalCount, int pageIndex, int pageSize)
- {
- return new PagedList<T>(source, totalCount, pageIndex, pageSize);
- }
- }
NHibernateExtensions.cs – this is where the NHibernate goodness comes in. This warrants a little explanation but take a look first and see if you can see what’s going on.
NHibernateExtensions.cs
- public static class NHibernateExtensions
- {
- public static PagedList<T> PagedList<T>(this ICriteria criteria, ISession session, int pageIndex, int pageSize) where T: class
- {
- if (pageIndex < 0)
- pageIndex = 0;
- var countCrit = (ICriteria)criteria.Clone();
- countCrit.ClearOrders(); // so we don't have missing group by exceptions
- var results = session.CreateMultiCriteria()
- .Add<long>(countCrit.SetProjection(Projections.RowCountInt64()))
- .Add<T>(criteria.SetFirstResult(pageIndex * pageSize).SetMaxResults(pageSize))
- .List();
- var totalCount = ((IList<long>)results[0])[0];
- return new PagedList<T>((IList<T>)results[1], totalCount, pageIndex, pageSize);
- }
- }
First of all, this method is an extension of NHibernate’s ICriteria class so it obviously requires you to be using NHibernate’s Criteria API. This type of thing would be much more difficult using the HQL syntax.
Essentially what we want to do is leverage NHibernate’s multi-criteria feature to send two different SQL statements to the server at the same time. One to retrieve the total record count of the query and two to get the actual results of that query, limited to the page size and page index that we specify. That’s why we Clone the original criteria that is passed into the method. This will be what is used to get the total record count for the query. We call the ClearOrders method on this instance of the ICriteria because: 1) we don’t care about how the query is ordered if we’re just getting the total row count; and 2) the order statements can cause problems if there are groupings in the criteria. Trust me on this.
We then create the multi-criteria object on line 11 and add the total row count criteria that we cloned and the original criteria passed in but we use the SetFirstResult and SetMaxResults methods to limit the number of records returned.
Finally, we retrieve the values from the two result sets. The first being the total row count. The second, the actual results of the query and return the results using our fancy new PagedList<T> class.
The usage of this extension method couldn’t be simpler.
Code Snippet
- public PagedList<Order> GetCompletedOrders(int pageIndex, int pageSize)
- {
- // _currentSession is an instance of ISession, instantiation not shown
- return _currentSession.CreateCriteria<Order>()
- .Add(Expression.Eq("Status", (int)OrderStatus.Complete))
- .AddOrder(Order.Desc("OrderCompletedDate"))
- .PagedList<Order>(_currentSession, pageIndex, pageSize);
- }
As a bonus, I’m going to post some code that I use in my ASP.NET MVC projects that allows you generate a Pager control complete with customizable, CSS classes, next/previous text customizations, AJAX support, etc. from our PagedList<T> class in ONE LINE OF CODE. Stay tuned…
Update: here’s the post on those ASP.NET MVC Pager helper classes I mentioned.
Comments
Anonymous
November 20, 2012
Excellent! One small addition to make PagedList work with Linq, implement IEnumerable: public class PagedList<T> : IPagedList, IEnumerable<T> { public IEnumerator<T> GetEnumerator() { return Items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return Items.GetEnumerator(); } }Anonymous
January 15, 2014
Need little help, how will I pass my list or data class object to PageList. Please explain. for example - List<User> userList = FetchData(); Now how to pass List<User> to PagedList. Thanks.