Zubair Zubair - 3 months ago 26
C# Question

How to handle null value in entity framework sum function

Screenshot

My code is here:

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


That work fine but through Error database is empty


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


I want replace it with 0 (zero)

I am using entity frame work with MVC application

Answer

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`