Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the maximum value in NHibernate?

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
like image 570
Sasha Avatar asked Nov 28 '22 04:11

Sasha


2 Answers

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

like image 200
tolism7 Avatar answered Dec 10 '22 07:12

tolism7


Session.Query<Page>().Max(x => (int?)x.PageOrder)

Note the cast (I'm assuming PageOrder is an int)

like image 23
Diego Mijelshon Avatar answered Dec 10 '22 05:12

Diego Mijelshon