If there are no records that match the following lambda query, I get a
System.InvalidOperationException error. Additional information: 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.
runTime = db.Records.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x).Sum(c => c.RunMinutes);
runTime
decimal
decimal?
Firstly you can select decimal values from the objects which met the condition. And then use .DefaultIfEmpty()
method before the .Sum()
method:
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Select(c => c.RunMinutes)
.DefaultIfEmpty()
.Sum();
DefaultIfEmpty()
function inserts a single element with a default value if the sequence is empty. And as we know, defualt value for decimal
type is 0.0M
.
(Default Values Table)
Additionally:
You didn't tell us Linq to What? are you using. But, if you are using LinqToEntity, then you must change your code as (DefaultIfEmpty
is not supported by EF):
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Sum(c => (decimal?)c.RunMinutes) ?? 0;