Bill Greer Bill Greer - 2 months ago 17
C# Question

How do I check my lambda expression for null?

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?

Answer

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;
Comments