mvc使用linq to sql进行sum统计遇到查询为null的问题

mvc linq to sql,linq to entity,sum,null

昨天写了段sum的统计语句,

decimal sums

sums = (
from fac in db.Apply
where  fa.state == 1
select fac.num
).Sum(),

然后一运行,报错

Message=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.

因为查询为空。在网上纠结了很久,找到一个方法,小改一下

select new{ s=fac.num}).Sum(x=>x.s as decimal?),

这么一改后,在LinqPad5上测试通过,但是实际在程序上会报

Message=The 'TypeAs' expression with an input of type 'System.Decimal' and a check of type 'System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported. Only entity types and complex types are supported in LINQ to Entities queries.

头大,这同样的Linq to sql,怎么就不行了呢?

继续查,

可行办法是

select fac.num
).DefaultIfEmpty(0).Sum(),这样就OK了。

另外,SqlFunction在linq to entity中用不了,我使了后都会报错,暂时不明原因,目前也没时间去解决这个问题。

posted @   lythen  阅读(2498)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示