如何检查我的空lambda表达式? [英] How do I check my lambda expression for null?

查看:223
本文介绍了如何检查我的空lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有符合下列拉姆达查询没有记录,我得到一个

If there are no records that match the following lambda query, I get a

System.InvalidOperationException错误。其他信息:演员价值型System.Decimal失败,因为物化值为null。 。无论结果类型的泛型参数或查询必须使用可空类型

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.

中的代码是:运行= 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?

推荐答案

首先,你可以从中选择满足条件的对象十进制值。然后使用 .DefaultIfEmpty() .SUM()方法之前的方法:

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()函数插入一个元素用默认值,如果序列为空。正如我们知道的,小数类型defualt值为 0.0M
(默认值表)

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:

您没有告诉我们的Linq到的 的?您正在使用什么。但是,如果你使用的是LinqToEntity,那么你必须改变你的代码( DefaultIfEmpty 不是由EF支持):

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;

这篇关于如何检查我的空lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆