Posts Tagged ‘linq to objects’

LinqToSql Sum over empty collection causes exception

October 15, 2010 Leave a comment

Linq to Sql Sum method over empty collection returns null. Linq to object Sum method over empty collection returns 0.

This Linq To Sql behavior can cause exception :

"The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type."

This will happen if you try to assign sum to decimal. Decimal is not nullable. If sum is called over empty collection (e.g. no items are return from where clause) sum will try to return null. decimal is not nullable and you have exception Sad smile

One solution is to cast sum so it returns nullable decimal (decimal ?), Second solution is to use linq to object, because, linq to object sum over empty collection returns 0.

Why is all this happening?

In SQL, Sum() aggregate operator returns null for an empty set. So this is as designed.

Since users often rely on LINQ to SQL producing the same results as an equivalent SQL query, we decided not to convert the null to zero as in case of LINQ to Objects. There are a number of cases where we considered forcing .NET/C#/VB semantics for consistency with LINQ to Objects vs retaining SQL semantics for consistency with SQL. In most cases, we favored the latter for consistency and more enforceable and performant implementation,




You can read more about this issue on