使用LINQ过滤DBNull

Ste*_*ven 5 linq vb.net null dbnull

NULL当我明确过滤掉Where子句中的那些行时,为什么以下查询会为具有桶值的行引发下面的错误?

Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
            Where Not IsDBNull(row.Cal) AndAlso tiCal_drop.Text = row.Cal _
            AndAlso Not IsDBNull(row.Tran) AndAlso tiTrans_drop.Text = row.Tran _
            AndAlso Not IsDBNull(row.barrel) _
            Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Run Code Online (Sandbox Code Playgroud)

Run-time exception thrown : System.Data.StrongTypingException - The value for column 'barrel' in table 'conformal' is DBNull.

如何重写我的查询/条件以按照我的意图工作?

Tho*_*que 7

默认情况下,在强类型数据集中,如果字段为null,则属性会抛出该异常.您需要使用生成的Is[Field]Null方法:

Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
            Where Not row.IsCalNull() AndAlso tiCal_drop.Text = row.Cal _
            AndAlso Not row.IsTranNull() AndAlso tiTrans_drop.Text = row.Tran _
            AndAlso Not row.IsbarrelNull() _
            Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Run Code Online (Sandbox Code Playgroud)

或者DataRow.IsNull方法:

Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
            Where Not row.IsNull("Cal") AndAlso tiCal_drop.Text = row.Cal _
            AndAlso Not row.IsNull("Tran") AndAlso tiTrans_drop.Text = row.Tran _
            AndAlso Not row.IsNull("barrel") _
            Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Run Code Online (Sandbox Code Playgroud)