使用LINQ过滤DBNull

时间:2010-03-08 16:43:44

标签: vb.net linq 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-time exception thrown : System.Data.StrongTypingException - The value for column 'barrel' in table 'conformal' is DBNull.

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

2 个答案:

答案 0 :(得分: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)

或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)

答案 1 :(得分:0)

这对我有用。

Dim query = From row As dbDataSet.conformalRow
        In dbDataSet.Tables("conformal") _ 
        Where row.Cal.Length > 0 AndAlso tiCal_drop.Text = row.Cal _ 
            AndAlso row.Tran.Length > 0 AndAlso tiTrans_drop.Text = row.Tran _ 
            AndAlso row.barrel.Length > 0 _ 
        Select row.barrel