从数据表中填充对象的默认值时的DBNull
-
19-09-2019 - |
题
我填充客户对象,如下所示。如何将我的代码简洁类似以下?
If IsDbNull(.Age) Then
.Age = 10
Else
.Age = dataRow("Age")
End If
下面是我想使用它的上下文:
Public Shared Function Retrieve() As List(Of Customer)
Dim dt As DataTable = Dac.ExecuteDataTable("CustomerRetrieveAll", Nothing)
Dim customerList As New List(Of Customer)
For Each dr As DataRow In dt.Rows
customerList.Add(New Customer {
.CustomerId = CType(dr("CustomerID"), Integer),
.LastName = dr("LastName").ToString,
.Age = dr("Age").ToString,
.FirstName = dr("FirstName").ToString})
Next
Return customerList
End Function
解决方案
在Microsoft.VisualBasic
命名空间有一个叫做IIF
功能。它通过计算表达式并返回一个值,如果如果假表达式为真和另一个。
所以
.Age = IIF(dr("Age") = DBNull.Value, 10, dr("Age").ToString())
在Visual Studio中(2008〜)的较新版本,这是默认提供无需导入的导入(IIF
是一个功能,新If
是操作者):
.Age = If(dr("Age") = DBNull.Value, 10, dr("Age").ToString())
如果它没有DBNull
,只是Nothing
,您可以使用空合并运算符:
Dim val = If(objectThatMightBeNothing, DefaultValueToUse)
请参阅 MSDN 获得更多的细节。
其他提示
你试试这个:
.Age = IIf(dr("age") is DbNull, 10, dr("age"))
希望它能帮助。
年龄能有什么价值,如果它包含空?点击 我建议使用可为空(整数)为年龄。
另外,比较它针对DBNull.Value(其用于在基础字段包含空值的情况下比较)。
不隶属于 StackOverflow