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.
The code is: runTime = db.Records.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x).Sum(c => c.RunMinutes);
The variable runTime
is a decimal
. I tried changing it to a decimal?
but I still get the same error.
What is the correct approach to solve this problem?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With