【问题标题】:'DBNULL error' while summing column on datatable using LINQ使用 LINQ 对数据表上的列求和时出现“DBNULL 错误”
【发布时间】:2015-10-08 17:34:27
【问题描述】:

我确信这是一个非常简单的问题,但我似乎无法在任何地方找到答案......

我正在尝试使用 linq 对数据表中的数值求和,但是因为 K 列中也有空值,所以我收到了一个错误: Cannot cast DBNull.Value to type 'System.Int32'. Please use a nullable type. 克服此错误的正确语法是什么?

   Private table1 As DataTable
Private Function getIncome(ByVal acName As String, ByVal acTeam As String) As Integer
    Dim query = table1.AsEnumerable().Where(Function(x) x.Field(Of String)("G") = acName AndAlso x.Field(Of String)("F") = acTeam _
                    ).Sum(Function(x) x.Field(Of Integer)("K"))

    Dim total As Integer = query
    Return total
End Function 

【问题讨论】:

    标签: vb.net linq


    【解决方案1】:

    这一行:

    Sum(Function(x) x.Field(Of Integer)("K"))

    应该替换为:

    Sum(Function(x) x.Field(Of Integer?)("K"))

    如果返回DBNull.Value,则使用Field<T>() 方法返回(0) int 的默认值,因此可以安全使用,请在此处查看我对此的其他答案

    Object initializing with db null check

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      相关资源
      最近更新 更多