Why LINQ to Entity Sum Returns Null for Empty Result Set

linq

There are quite a few questions on Stack Overflow about the Linq to Entity / Linq to SQL Sum extension method, about how it returns null when the result set is empty: 1, 2, 3, 4, 5, 6, 7, and many more, as well as a blog post discussing the issue here. I feel it is an inconsistency in the Linq implementation.

I am assuming at this point that it is not a bug, but is more or less working as designed. I understand that there are workarounds (for example, casting the field to a nullable type, so you can coalesce with ??), and I also understand that for the underlying SQL, a NULL result is expected for an empty result set.

But because the result of the Sum extension for non-nullable types is also non-nullable, why does the Linq to SQL / Linq to Entity Sum behave this way?

Best Answer

The problem isn't that EF or LINQ2SQL return null for an empty set, it's that SQL returns null. Along those lines, what would you expect EF or LINQ2SQL to return when attempting to sum on a null value?

Generally, a null value is not a candidate for mathematical functions. Null usually means something along the lines of "unknown value" and is not the same as zero (the default value of an int or decimal in .NET). You can't perform math on it.

As such, it would be improper for the framework to decide to always substitute a default value for a null value and proceed to give you a misleadingly precise sum. Instead, the framework properly complains that the sum operation is impossible (because of the null value) and it is left to the caller to decide what to do in the case of a null value, using the techniques you have described and linked to in your question.