How can I select the maximum value in NHibernate?

Sasha picture Sasha · Jan 21, 2011 · Viewed 15.1k times · Source

I need to get maximum page order from database:

int maxOrder = GetSession.Query<Page>().Max(x => x.PageOrder);

The above works if there are rows in the database table, but when table is empty I'm getting:

Value cannot be null.
Parameter name: item

Answer

tolism7 picture tolism7 · Jan 21, 2011

In the way you are doing it is normal to get an exception as the enumerable, that the GetSession.Query<Page>() returns, is empty (because the table is empty as you mentioned).

The exception that you should be getting is: Sequence contains no elements. The exception you mention in your question is because the item variable (which is irrelevant with the NHiberanate query you list above) is null (line 54 assigns the item property to null).

A safer way to get the max from a property in a table would be the following:

var max = GetSession.CreateCriteria<Page>()
                .SetProjection(Projections.Max("PageOrder"))
                .UniqueResult();

or using QueryOver with NHibenrate 3.0:

var max = GetSession.QueryOver<Page>()
      .Select(
            Projections
               .ProjectionList()
               .Add(Projections.Max<Page>(x => x.PageOrder)))
      .List<int>().First();

If the table is empty you will get max = 0