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

c# – MVC linq到sql sum

发布时间:2020-12-15 18:07:51 所属栏目:百科 来源:网络整理
导读:尝试根据字段的总和获取从数据库返回的值. 但得到这个消息: 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 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.

数据库在当天不包含该用户的记录是有效的,因此我沿着可空路线走了.在过去的好日子里,我会在其中建立一个带有“ISNULL”的存储过程!

这是我的基本表达方式:

十进制? foodCount = dbContext.fad_userFoods.Where(uf => uf.dateAdded == thisDate&& uf.userID == thisGuid).Sum(uf =>(decimal?)uf.quantityAmount ?? 0m);

谷歌搜索它提出了可空的定义和使用?用“m”作为小数.但仍然存在错误!

您的集体帮助将一如既往地无价之宝.提前致谢.

解决方法

使用 DefaultIfEmpty方法.如果没有找到任何值,则将填入0.
decimal foodCount = dbContext.fad_userFoods
    .Where(uf => uf.dateAdded == thisDate && uf.userID == thisGuid)
    .Select(uf => uf.quantityAmount)
    .DefaultIfEmpty()
    .Sum();

(编辑:李大同)

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

    推荐文章
      热点阅读