How to check lambda expression for null?

If there are no entries matching the following lambda query, I get

Error System.InvalidOperationException. Additional information: The given value type "System.Decimal" failed because the materialized value is null. Either the general parameter of the result type, or the query should use a type with a null value.

Code: runTime = db.Records.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x).Sum(c => c.RunMinutes);

The variable runTime is decimal . I tried changing it to decimal? but I still get the same error.

What is the right approach to solve this problem?

+6
source share
1 answer

First, you can select decimal values ​​from objects that satisfy the condition. And then use the .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 you know, the value of defualt for type decimal 0.0M . (Table of default values)

Additionally

You did not tell us Linq to What? . But if you use LinqToEntity, then you should change your code, since ( DefaultIfEmpty 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; 
+23
source

Source: https://habr.com/ru/post/981835/


All Articles