使用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了。

还有一种

.Sum(a => (decimal?)a.num) ?? 0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值