加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何检查我的lambda表达式是否为null?

发布时间:2020-12-15 18:19:13 所属栏目:百科 来源:网络整理
导读:如果没有匹配以下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 parame
如果没有匹配以下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是小数.我尝试将其更改为小数?但我仍然得到同样的错误.

解决这个问题的正确方法是什么?

解决方法

首先,您可以从满足条件的对象中选择十进制值.然后在.Sum()方法之前使用 .DefaultIfEmpty()方法:
runTime = db.Records
              .Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
              .Select(c => c.RunMinutes)
              .DefaultIfEmpty()
              .Sum();

如果序列为空,则DefaultIfEmpty()函数会插入具有默认值的单个元素.而且我们知道,十进制类型的defualt值是0.0M.
(Default Values Table)

另外:

你没告诉我们Linq什么?你正在用吗.但是,如果您使用LinqToEntity,则必须将代码更改为(EF不支持DefaultIfEmpty):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读