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

  • 相关阅读:
    CentOS7 网络管理相关命令
    CentOS7配置双网卡绑定
    ajax请求
    django向数据库添加数据
    django基于正则的url匹配
    django前端到后端一次简单完整的请求实例
    django数据库动态添加列
    django1.9 创建项目和app并初始化项目
    django1.9 创建数据表
    数据结构和算法(5)-树
  • 原文地址:https://www.cnblogs.com/lythen/p/8202484.html
Copyright © 2011-2022 走看看