使用db null检查初始化的对象 [英] Object initializing with db null check
问题描述
我正在尝试使用数据集中的数据库返回的数据来初始化对象,如下所示:
I am trying to initialize an object with data from database return in a dataset as below:
Class Pdf
Public FileId As Integer
Public AccountNumber As Integer
Public DateSaved As DateTime
Public FileName As String
Public DateImported As DateTime
场景1
我可以这样初始化对象:
Scenerio 1 I can intialize the object like this:
Dim pdf = New Pdf With {.FileId = ds.Tables(0).Rows(i)("fileid"),
.AccountNumber = ds.Tables(0).Rows(i)("accountnumber"),
.DateSaved = ds.Tables(0).Rows(i)("datesaved"),
.FileName = ds.Tables(0).Rows(i)("filename"),
.DateImported = ds.Tables(0).Rows(i)("dateimported")
}
但这不起作用,因为列数据可以为空,但我不能如果如何执行db null检查这种方法。
But this is not working, because column data can be null and I am not if how to do a db null check in this approach.
然后我有场景2 :
Dim pdf As New pdf
If Not IsDBNull(ds.Tables(0).Rows(i)("fileid")) Then
PdfFileId = ds.Tables(0).Rows(i)("fileid")
Else
PdfFileId = 0
End If
If Not IsDBNull(ds.Tables(0).Rows(i)("accountnumber")) Then
pdf.AccountNumber = ds.Tables(0).Rows(i)("accountnumber")
Else
pdf.AccountNumber = 0
End If
If Not IsDBNull(ds.Tables(0).Rows(i)("datesaved")) Then
pdf.DateSaved = Format(ds.Tables(0).Rows(i)("datesaved"), "yyyy-MM-dd")
Else
pdf.DateSaved = Nothing
End If
If Not IsDBNull(ds.Tables(0).Rows(i)("dateimported")) Then
pdf.DateImported= Format(ds.Tables(0).Rows(i)("dateimported"), "yyyy-MM-dd")
Else
pdf.DateImported= Nothing
End If
结束这样可以避免执行以下许多 If
语句。在我看来,这种方式效率低下,有人可以在场景一或两种情况下提出更好的初始化对象的方法吗?如果问题不清楚,请让我知道,我会尽力解释。
How can I do this to avoid doing so many If
statements below. This way seems inefficient to me, can anyone suggest an better approach to initializing the object in scenario one or two? If the question is unclear, please do let me know, I will try and explain.
请注意,这是示例数据。
Please note this is sample data.
推荐答案
从阅读 T字段< T>(此DataRow行,字符串columnName)
中,我相信有一个检查引用和值类型的DBNull.Value,如果传递 DBNull.Value
,则返回默认值。
From reading T Field<T>(this DataRow row, string columnName)
, I believe that there is a check for the DBNull.Value for both reference and value types, returning a default value if DBNull.Value
is passed.
因此您可以使用它代替每次检查 DBNull.Value
:
So you can use it instead of checking for DBNull.Value
each time:
.FileName = ds.Tables(0).Rows(i).Field(Of String)( FileName)
如果指定的DataColumn的值为null,并且T为引用类型或可为null的类型,则返回类型将为null。字段方法将不返回Value。
If the value of the specified DataColumn is null and T is a reference type or nullable type, the return type will be null. The Field method will not return Value.
由于您无法使用它,因此提供了@TimSchmelter您可以基于的答案:
Since you cant use this then @TimSchmelter provided an answer which you could build upon:
.FileId = If(row.IsNull( fileid),0,Convert.ToInt32(row (文件ID))
这篇关于使用db null检查初始化的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!