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

StackOverflow https://stackoverflow.com/questions/8436677

  •  11-03-2021
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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

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"))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top