我正在使用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)
那么如何优雅地设置null整数或布尔值呢?我已经在C#中看到了建议,但它们没有正确转换为VB,给出'TryCast操作数必须是引用类型,但是整数?是值类型'编译器错误 .
3 回答
我在这种情况下使用以下函数:
您的代码看起来像这样:
请注意,如果值为DbNUll作为第二个参数,则此函数要求您传递应使用的值 .
您可以利用SqlDataReader的IsDBNull方法并使用VB.NET ternary operator为poco对象指定默认值
它只是一行,不是很优雅,因为你需要调用两次GetOrdinal方法 .