Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check my lambda expression for null?

Tags:

c#

lambda

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?

like image 244
Bill Greer Avatar asked Feb 01 '15 17:02

Bill Greer


1 Answers

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;
like image 145
Farhad Jabiyev Avatar answered Oct 13 '22 03:10

Farhad Jabiyev