我正在尝试使用linq对数据表中的数值求和,但因为列UniteDispo
中也有空值我收到错误:
无法将DBNull.Value强制转换为' Decimal'。请使用可空类型。
这是我的代码:
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
克服此错误的正确语法是什么?
答案 0 :(得分: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