Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null value in entity framework sum function

Tags:

c#

linq-to-sql

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

like image 486
Zubair Avatar asked Sep 19 '15 16:09

Zubair


1 Answers

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;

like image 111
Wrightboy Avatar answered Oct 10 '22 04:10

Wrightboy