Why does Linq to Entity Sum return null when the result set is empty?

Posted by Hannele on Programmers See other posts from Programmers or by Hannele
Published on 2014-08-20T14:25:09Z Indexed on 2014/08/20 22:32 UTC
Read the original article Hit count: 139

Filed under:

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?

© Programmers or respective owner

Related posts about LINQ