Skip to content

Getting a range of records using SetFirstResult and SetMaxResults with ordering in NHiberante

February 2, 2012

A problem that I needed to readdress in looking at was getting n records for caching in NHibernate with column ordering, I found that I had to write a SQL query inside CreateQuery to do the ordering but couldn’t perform getting a range of records (n) from a starting index. Here was the initial code

IQuery query = SessionFactoryContext.GetCurrentSession().CreateSQLQuery(“SELECT Username, ClientIPAddress, StartDateTime, EndDateTime FROM ( SELECT Username, ClientIPAddress, StartDateTime, EndDateTime, ROW_NUMBER() OVER (ORDER BY ” + orderBy + “) AS row FROM dbo.userdata) a WHERE Username='” + username + “‘ AND row >= ” + firstRecord + ” AND row < ” + firstRecord + 100)
return (IList<PortalSession>)query.List<PortalSession>();

After investigating the issue further, and googling the solution. The findings shown were that you can use the ICriteria methods built into NHiberante to solve the problem, and you can split the string to get the order by components if you are using a DataGrid. Here is the solution: –

public static IList<DefinedType> GetAllRecordsByUserName(int firstRecord, string username, string orderBy)

ICriteria criteria;

string[] command = orderBy.Split(‘ ‘);

if (command[1].Equals(“asc”))
criteria = SessionFactoryContext.GetCurrentSession().CreateCriteria<DefinedType>();
criteria.Add(NHibernate.Criterion.Expression.Eq(“Username”, username));
criteria = SessionFactoryContext.GetCurrentSession().CreateCriteria<DefinedType>();
criteria.Add(NHibernate.Criterion.Expression.Eq(“Username”, username));

return (IList<DefinedType>)criteria.List<DefinedType>();


DefinedType is a custom type you have used.

Please note that I just used a simple select query in the sql statement, here I was trying to do somethign fancy, and it actually didn’t work in NHibernate due to mapping issues.


From → Uncategorized

Leave a Comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: