如何在实体框架求和函数中处理空值 [英] How to handle null value in entity framework sum function

查看:30
本文介绍了如何在实体框架求和函数中处理空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在这里:

Int64? amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => x.Price);

可以,但是通过错误数据库为空

That work fine but through Error database is empty

强制转换为值类型 'System.Int32' ,因为实例化值为null.结果类型的泛型参数或查询必须使用可空类型.

The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

我想将其替换为0(零)
我在MVC应用程序中使用实体框架工作

I want replace it with 0 (zero)
I am using entity frame work with MVC application

推荐答案

尝试一下

var amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => x.Price ?? 0);

如注释中所述,如果 Price 不可为空.
所以,用这个

If Price is not nullable, as mentioned in comments.
so, use this

var amount = db.Items.Where(x => x.ItemOrdered == true).Sum(x => x.Price);
// for null check for amount use `?? 0`

这篇关于如何在实体框架求和函数中处理空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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