I got this error when i use sum function in LINQ:
The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
GroupProduct.Where(a => a.Product.ProductID==1).Sum(Content => Content.Amount==null?0:Content.Amount),
This looks like it should work (and usually does) but fails when the Where() method returns null:
The error:
"The cast to value type 'Decimal' failed because the materialized value is null"
is due to the Sum() method returning null (not zero) when summing over an empty set.Either of these work for me:
This is what I usually use. This will cover the possibility of
Amount
being null and also cover the possibility of an empty set.DefaultIfEmpty()
returns the default value associated withAmount
's type, which isint
, in which case the default value is0
.Try this:
Did you try the following:
The code from my application looks like:
You could exclude at source?