Quantcast
Channel: Development With A Dot
Viewing all articles
Browse latest Browse all 404

NHibernate Pitfalls: Aggregating Non-Nullable Numerical Values Without Records

$
0
0

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();

Viewing all articles
Browse latest Browse all 404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>