Paging fetch result of NHibernate

Two solutions available for paging fetch result:

  1. SetFirstResult/SetMaxResult when using NHibernate detached queies. Ayende has a good example.
  2. Skip()/Take() when using NHibernate.Linq

I personally like the latter because it’s strongly typed. Performance are same, both with TOP(N) in the generated SQL.

Only issue remaining, how to pass the total count back to service/UI? Options

  1. Using out parameter keyword, as this example.
  2. Create my own Page<T> class to organize the fetch result, similar to the Pager class in Karl’s ModelQuery

Code:  (This one has a double query problem)


public Page<Organization> FetchOrganizationWithNameContains(string orgNamePart
   , int indexOfPage, int resultsPerPage)
{
    var result = new Page<Organization>();

    var query = Session.Linq<Organization>().Where(x => x.Name.Contains(orgNamePart));

    result.Entities = query.Skip((indexOfPage - 1)*resultsPerPage)
        .Take(resultsPerPage).ToArray();

    result.TotalCount = query.Count();

    return result;
 }

Advertisements

4 thoughts on “Paging fetch result of NHibernate

  1. Session is property holding NHibernate Session, we made it available in our repository classes.
    This post was created using NHibernate2Linq, if we do it today we would use IQueryable in NH3.
    Thanks for feedback.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s