How can you do paging with NHibernate?

.NetNhibernateOrmPagination

.Net Problem Overview


For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this?

.Net Solutions


Solution 1 - .Net

ICriteria has a SetFirstResult(int i) method, which indicates the index of the first item that you wish to get (basically the first data row in your page).

It also has a SetMaxResults(int i) method, which indicates the number of rows you wish to get (i.e., your page size).

For example, this criteria object gets the first 10 results of your data grid:

criteria.SetFirstResult(0).SetMaxResults(10);

Solution 2 - .Net

You can also take advantage of the Futures feature in NHibernate to execute the query to get the total record count as well as the actual results in a single query.

Example

 // Get the total row count in the database.
var rowCount = this.Session.CreateCriteria(typeof(EventLogEntry))
	.Add(Expression.Between("Timestamp", startDate, endDate))
	.SetProjection(Projections.RowCount()).FutureValue<Int32>();

// Get the actual log entries, respecting the paging.
var results = this.Session.CreateCriteria(typeof(EventLogEntry))
	.Add(Expression.Between("Timestamp", startDate, endDate))
	.SetFirstResult(pageIndex * pageSize)
	.SetMaxResults(pageSize)
	.Future<EventLogEntry>();

To get the total record count, you do the following:

int iRowCount = rowCount.Value;

A good discussion of what Futures give you is here.

Solution 3 - .Net

From NHibernate 3 and above, you can use QueryOver<T>:

var pageRecords = nhSession.QueryOver<TEntity>()
            .Skip((PageNumber - 1) * PageSize)
            .Take(PageSize)
            .List();

You may also want to explicitly order your results like this:

var pageRecords = nhSession.QueryOver<TEntity>()
            .OrderBy(t => t.AnOrderFieldLikeDate).Desc
            .Skip((PageNumber - 1) * PageSize)
            .Take(PageSize)
            .List();

Solution 4 - .Net

public IList<Customer> GetPagedData(int page, int pageSize, out long count)
        {
            try
            {
                var all = new List<Customer>();

                ISession s = NHibernateHttpModule.CurrentSession;
                IList results = s.CreateMultiCriteria()
                                    .Add(s.CreateCriteria(typeof(Customer)).SetFirstResult(page * pageSize).SetMaxResults(pageSize))
                                    .Add(s.CreateCriteria(typeof(Customer)).SetProjection(Projections.RowCountInt64()))
                                    .List();

                foreach (var o in (IList)results[0])
                    all.Add((Customer)o);

                count = (long)((IList)results[1])[0];
                return all;
            }
            catch (Exception ex) { throw new Exception("GetPagedData Customer da hata", ex); }
      }

When paging data is there another way to get typed result from MultiCriteria or everyone does the same just like me ?

Thanks

Solution 5 - .Net

How about using Linq to NHibernate as discussed in http://www.ayende.com/Blog/archive/2007/03/20/Linq-For-NHibernate-Orderring-and-Paging.aspx">this blog post by Ayende?

Code Sample:

(from c in nwnd.Customers select c.CustomerID)
        .Skip(10).Take(10).ToList(); 

And here is a detailed post by the NHibernate team blog on http://www.nhforge.org/blogs/nhibernate/archive/2008/08/31/data-access-with-nhibernate.aspx">Data Access With NHibernate including implementing paging.

Solution 6 - .Net

Most likely in a GridView you will want to show a slice of data plus the total number of rows (rowcount) of the total amount of data that matched your query.

You should use a MultiQuery to send both the Select count(*) query and .SetFirstResult(n).SetMaxResult(m) queries to your database in a single call.

Note the result will be a list that holds 2 lists, one for the data slice and one for the count.

Example:

IMultiQuery multiQuery = s.CreateMultiQuery()
    .Add(s.CreateQuery("from Item i where i.Id > ?")
            .SetInt32(0, 50).SetFirstResult(10))
    .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
            .SetInt32(0, 50));
IList results = multiQuery.List();
IList items = (IList)results[0];
long count = (long)((IList)results[1])[0];

Solution 7 - .Net

I suggest that you create a specific structure to deal with pagination. Something like (I'm a Java programmer, but that should be easy to map):

public class Page {
   
   private List results;
   private int pageSize;
   private int page;
   
   public Page(Query query, int page, int pageSize) {
       
       this.page = page;
       this.pageSize = pageSize;
       results = query.setFirstResult(page * pageSize)
           .setMaxResults(pageSize+1)
           .list();
   
   }
   
   public List getNextPage()
   
   public List getPreviousPage()

   public int getPageCount()

   public int getCurrentPage()

   public void setPageSize()

}

I didn't supply an implementation, but you could use the methods suggested by @Jon. Here's a good discussion for you to take a look.

Solution 8 - .Net

You don't need to define 2 criterias, you can define one and clone it. To clone nHibernate criteria you can use a simple code:

var criteria = ... (your criteria initializations)...;
var countCrit = (ICriteria)criteria.Clone();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRayView Question on Stackoverflow
Solution 1 - .NetJon LimjapView Answer on Stackoverflow
Solution 2 - .NetJeremy DView Answer on Stackoverflow
Solution 3 - .NetLeandro de los SantosView Answer on Stackoverflow
Solution 4 - .NetBarbaros AlpView Answer on Stackoverflow
Solution 5 - .NetNotMyselfView Answer on Stackoverflow
Solution 6 - .NetzadamView Answer on Stackoverflow
Solution 7 - .NetMarcio AguiarView Answer on Stackoverflow
Solution 8 - .NetMarcinView Answer on Stackoverflow