如何检查我的 lambda 表达式是否为空?
How do I check my lambda expression for null?
如果没有匹配以下 lambda 查询的记录,我会得到
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?
,但我仍然遇到相同的错误。
解决这个问题的正确方法是什么?
首先你可以从满足条件的对象中select十进制值。然后在 .Sum()
方法之前使用 .DefaultIfEmpty()
方法:
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Select(c => c.RunMinutes)
.DefaultIfEmpty()
.Sum();
如果序列为空,DefaultIfEmpty()
函数插入一个具有默认值的元素。正如我们所知,decimal
类型的默认值为 0.0M
。
(Default Values Table)
另外:
您没有告诉我们您正在使用 Linq to What?。但是,如果您使用的是 LinqToEntity,那么您必须将代码更改为(DefaultIfEmpty
不受 EF 支持):
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Sum(c => (decimal?)c.RunMinutes) ?? 0;
如果没有匹配以下 lambda 查询的记录,我会得到
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?
,但我仍然遇到相同的错误。
解决这个问题的正确方法是什么?
首先你可以从满足条件的对象中select十进制值。然后在 .Sum()
方法之前使用 .DefaultIfEmpty()
方法:
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Select(c => c.RunMinutes)
.DefaultIfEmpty()
.Sum();
如果序列为空,DefaultIfEmpty()
函数插入一个具有默认值的元素。正如我们所知,decimal
类型的默认值为 0.0M
。
(Default Values Table)
另外:
您没有告诉我们您正在使用 Linq to What?。但是,如果您使用的是 LinqToEntity,那么您必须将代码更改为(DefaultIfEmpty
不受 EF 支持):
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Sum(c => (decimal?)c.RunMinutes) ?? 0;