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中用不了,我使了后都會報錯,暫時不明原因,目前也沒時間去解決這個問題。