How to handle null value in entity summation function

Screenshot

My code is here:

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

This works fine, but through the error database is empty

The value type is discarded because the materialized value is null. Either the general parameter of the result type, or the query should use a type with a null value. 'System.Int32'

I want to replace it with 0 (zero)
I use the object frame work with MVC application

+5
source share
3 answers

try it

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

EDIT: If Pricenot null as indicated in the comments.
so use this

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

Another option is to filter out the null values:

var amount = db.Items.Where(x => x.ItemOrdered == true && x.Price != null).Sum(x => x.Price);
+2

The problem is NOT that the Price data type is Nullable. In fact, the problem is that it is NOT nullified and there is an empty set. The EF function Sum()can only work with empty sets if it deals with nullable data. I know this does not make sense, because empty sets and types that allow NULL values โ€‹โ€‹are not the same thing. Just cast it to a nullable type and you will get a nullable answer. In the case of an empty set, the answer will be zero. So this is the only case that will work.

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

Source: https://habr.com/ru/post/1608151/


All Articles