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中用不了,我使了后都会报错,暂时不明原因,目前也没时间去解决这个问题。