Tag: Paging

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)

    result.TotalCount = query.Count();

    return result;