How to handle null value in entity framework sum function

Try this

var amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => x.Price ?? 0);

EDIT: If Price is not nullable, as mentioned in comments.
so, use this

var amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => x.Price);
// for null check for amount use `?? 0`

The problem is NOT that the 'Price' data type is nullable. Actually the problem is that its NOT nullable and there is an empty set. The EF Sum() function can only deal with empty sets if its dealing with nullable data. I know this makes no sense since empty sets and nullable types are not the same thing at all. Just cast it to a nullable type and you will get a nullable response. In the empty set case the response will be null. So thats the only case that will work.

Int64? amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => (Int64?) x.Price);

For anyone having issues because Price is not nullable but the where clause is returning an empty set you can just cast price to be nullable but then move the null coalescing check outside:

Int64 amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => (Int64?) x.Price) ?? 0;

Tags:

C#

Linq To Sql