SQL数据读取器 - 如何优雅地处理空列值

Rob*_*own 3 vb.net sqldatareader

我正在使用SQLDataReader从数据库中检索可能为null的值.我已经解决了如何处理Null字符串值,但无法使用相同的技巧来处理整数或布尔值:

Using cmd As DbCommand = store.GetStoredProcCommand("RetrievePOCO")
    store.AddInParameter(cmd, "ID", DbType.Int32, ID)
    Using reader As IDataReader = store.ExecuteReader(cmd)
        If reader.Read() = True Then
            Dim newPOCO As New POCO()
            With newPOCO
                'If the source column is null TryCast will return nothing without throwing an error
                .StatusXML = TryCast(reader.GetString(reader.GetOrdinal("StatusXML")), String)
                'How can a null integer or boolean be set elegantly?
                .AppType = TryCast(reader.GetInt32(reader.GetOrdinal("AppType")), System.Nullable(Of Integer))
                .Archived = TryCast(reader.GetBoolean(reader.GetOrdinal("Archived")), Boolean)
Run Code Online (Sandbox Code Playgroud)

那么如何优雅地设置null整数或布尔值呢?我已经在C#中看到了建议,但它们没有正确转换为VB,给出'TryCast操作数必须是引用类型,但是整数?是值类型'编译器错误.

dum*_*mmy 5

我在这种情况下使用以下函数:

Public Shared Function NoNull(ByVal checkValue As Object, ByVal returnIfNull As Object) As Object
    If checkValue Is DBNull.Value Then
        Return returnIfNull
    Else
        Return checkValue
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

您的代码看起来像这样:

With newPOCO
    .StatusXML = NoNull(reader("StatusXML"), "")
    .AppType = NoNull(reader("AppType"), -1)
    .Archived = NoNull(reader("Archived"), False)
End With
Run Code Online (Sandbox Code Playgroud)

请注意,如果值为DbNUll作为第二个参数,则此函数要求您传递应使用的值.