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
source share