NHibernate Pitfalls: Aggregating Non-Nullable Numerical Values Without Records
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:
1: var average = session.Query<Product>().Where(x => x.Price > 10000).Select(x => x.Price).Average();
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:
1: var average = session.Query<Product>().Where(x => x.Price > 10000).Select(x => (Decimal?) x.Price).Average();