How to choose the maximum value in NHibernate?

I need to get the maximum page order from the database:

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

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

 Value cannot be null. Parameter name: item 
+4
source share
3 answers
 Session.Query<Page>().Max(x => (int?)x.PageOrder) 

Pay attention to the listing (I assume that PageOrder is an int)

+8
source

In the way you do this, it is normal to get an exception as an enumeration, returned by GetSession.Query<Page>() , is empty (because the table is empty, as you mentioned).

The exception you should get is: A sequence contains no elements. The exception you mentioned in your question is that the item variable (which is not related to the NHiberanate query above) is null (line 54 sets the item property to null).

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

 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

+13
source

If you are having problems with the QueryOver example using tolism7 (InvalidCastException), here is how I got started:

 var max = session.QueryOver<Page>() .Select(Projections.Max<Page>(x => x.PageOrder)) .SingleOrDefault<object>(); return max == null ? 0 : Convert.ToInt32(max); 
+5
source

Source: https://habr.com/ru/post/1336445/


All Articles