VB.NET:如何与数据库列值和可为空的类型结合使用?还是有更好的解决方案? [英] VB.NET: How do I use coalesce with db column values and nullable types? Or is there a better solution?
问题描述
我正在尝试执行与此处所述类似的操作,但是具有可为空的类型。
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;
在VB中,应该是这样:
In VB, it would be this:
Dim availableUnits As Int32 = If(unitsInStock, 0)
但是我正在使用db列(可以是DbNull)和可空类型(可以是Nothing)(与DbNull不同)。如果列是DbNull,我想返回Nothing,否则返回值。例如:
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
这只是愚蠢。有没有更好的方法可以将可空的db值转换成我不知道的可空变量?
Which is just silly. Is there a better way of getting nullable db values into nullable variables that I'm not aware of?
推荐答案
这很愚蠢,但是在设置时,您必须投射 Nothing
:
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"))
这篇关于VB.NET:如何与数据库列值和可为空的类型结合使用?还是有更好的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!