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

Friday, August 10, 2018 / mcchu28


Possibly save 1 hour of your time: This error happens when I am trying to sum a list of records based on a property value, but there are no records returned from the LINQ query.

The fix is to add cast to nullable decimal.

var total = query.Sum(x => (decimal?) x.Value);