VB.NET: How do I use coalesce with db column values and nullable types? Or is there a better solution?

时光怂恿深爱的人放手 提交于 2020-01-04 06:00:38

问题


I'm trying to do something similar to what's described here, but with nullable types.

http://www.csharp-station.com/Tutorials/Lesson23.aspx

int availableUnits = unitsInStock ?? 0;

In VB, it would be this:

Dim availableUnits As Int32 = If(unitsInStock, 0)

However I'm working with db columns, which could be DbNull, and nullable types, which can be Nothing (which is different to DbNull). If a column is DbNull, I want to return Nothing, otherwise return the value. For eg:

Dim availableUnits As Int32? = If(myDataReader("UnitsInStock").Value, Nothing)

The error I'm getting is "Specified cast is not valid" but I'm not sure why. I've tried this as well:

Dim availableUnits As Int32? = If(isDbNull(myDataReader("UnitsInStock").Value), myDataReader("UnitsInStock").Value, Nothing)

Which is messy and just results in the same error. The only thing that works is this:

Dim availableUnits As Int32?
If isDbNull(myDataReader("UnitsInStock").Value) Then
  availableUnits = myDataReader("UnitsInStock").Value
Else
  availableUnits = Nothing
End If

Which is just silly. Is there a better way of getting nullable db values into nullable variables that I'm not aware of?


回答1:


It is silly, but you have to cast the Nothing when you set it:

Dim availableUnits As Int32? = If(myDataReader.IsDBNull("UnitsInStock"), _
                                  CType(Nothing, Int32?), _
                                  myDataReader.GetInt32("UnitsInStock"))



回答2:


If using DataSets instead of DataReaders is an option for you, the DataRow.Field method knows how to handle Nullable variables properly:

Dim availableUnits = myDataRow.Field(Of Int32?)("UnitsInStock")



回答3:


As I mention in what turns out to be a very similar question you are best served by not using Nothing here, but rather New Int32?:

Dim availableUnits = If(myDataReader.IsDBNull("UnitsInStock"), _
                              New Int32?, _
                              myDataReader.GetInt32("UnitsInStock"))


来源:https://stackoverflow.com/questions/8436677/vb-net-how-do-i-use-coalesce-with-db-column-values-and-nullable-types-or-is-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!