Master
Master

Reputation: 2153

Sum a IQueryable Column with where clause

I have 2 queries. One to find where Value column is greater than 150,000 and i need the count of entries. The second one is the sum of that rather than count. The Count works perfectly but the sum crashes and provides this error

{"The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."}

Working code:

var excessCount = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Count()  : 0;

Crashing Code:

var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Sum(x => x.Value) : 0;

Upvotes: 1

Views: 4576

Answers (1)

Habib
Habib

Reputation: 223237

You can solve the issue by explicitly casting to decimal? in Sum like:

var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost
                                  .Where(x => x.Value > 150000)
                                  .Sum(x => (decimal?) x.Value) : 0;

The issue is due to generated SQL from LINQ expression, and at C# end it will try to return decimal which can't accommodate a null value, hence the error.

You may see: Linq To Entities: Queryable.Sum returns Null on an empty list

Upvotes: 2

Related Questions