This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
When you are performing a LINQ query that aggregates non-nullable numeric values – Sum, Average, for example – and the query does not return any values, you will get an exception. An example would be:
This is not specific to NHibernate, this behavior will be the same on LINQ to Objects as well, and it is caused by a null result trying to be assigned to a non-nullable variable.
The workaround is simple, just cast the result property to an appropriate nullable equivalent: