【问题标题】:How to prevent error conversion from DBNull value to Decimal in Linq query results如何防止在 Linq 查询结果中从 DBNull 值到 Decimal 的错误转换
【发布时间】:2016-12-15 15:15:08
【问题描述】:

我正在尝试使用 linq 对数据表中的数值求和,但因为 UniteDispo 列中也有空值,所以我收到了一个错误:

无法将 DBNull.Value 强制转换为“十进制”类型。请使用可为空的类型。

这是我的代码:

Dim query2 = (From order In tabDispoAnnee.AsEnumerable() _
    Where order.Field(Of Integer)("code_part") = tab.Rows(i).Item("code_part") And order.Field(Of Integer)("CodeTypeBien") = tab.Rows(i).Item("CodeTypeBien") _
    Group order By order!code_part, order!CodeTypeBien _
    Into unit = Sum(CDec(order("UniteDispo"))), ca = Sum(CDec(order("CADispo"))) _
    Select unit, ca).ToList

克服此错误的正确语法是什么?

【问题讨论】:

  • 添加Where 子句以过滤出具有NULL 值的记录

标签: vb.net linq


【解决方案1】:

添加Where 子句以过滤出具有NULL 值的记录。试试这个

Dim query2 = (From order In tabDispoAnnee.AsEnumerable() _
    Where order.Field(Of Integer)("code_part") = tab.Rows(i).Item("code_part") _ 
    And order.Field(Of Integer)("CodeTypeBien") = tab.Rows(i).Item("CodeTypeBien") _
    And order.Field(Of Integer?)("UniteDispo").HasValue _
    And order.Field(Of Double?)("CADispo").HasValue _
    Group order By order!code_part, order!CodeTypeBien _
    Into unit = Sum(CDec(order("UniteDispo"))), ca = Sum(CDec(order("CADispo"))) _
    Select unit, ca).ToList

【讨论】:

  • 这行不通我有这个错误:“'IsNot' 需要具有引用类型的操作数,但此操作数的值类型为'十进制'”
  • 不幸的是我有这个错误“指定的演员是无效的”
  • 您确定它以DecimalNULL 形式存储在数据库中吗?或者是文字?
  • 它应该是order.Field(Of Integer?)("UniteDispo").HasValueorder.Field(Of Single?)("CADispo").HasValue。见stackoverflow.com/a/15523970/832052。根据该帖子,OP在假设该值不是字符串时存在问题,而它是字符串。他正在检查 Nullable(正如我所建议的,根据您的信息),但他需要检查字符串 "NULL"。两个都试试
  • 感谢“djv”它的工作只是我将类型 Decimal 更改为 Double in
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
  • 2012-07-05
相关资源
最近更新 更多