Why does Linq to Entity Sum return null when the list 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
16:34 UTC
Read the original article
Hit count: 155
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. Now, I could go a flag these as duplicates, but I feel it is still 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 list.
But because the result of the Sum extension for nullable types is also not nullable, why would the Linq to SQL / Linq to Entity Sum have been designed to behave this way?
© Programmers or respective owner