An object-oriented programming language developed by Microsoft that can be used in .NET.
Hi @RogerSchlueter-7899 ,
Thank you for sharing the details. As Erland Sommarskog correctly pointed out, the key issue is that IsDBNull expects the zero-based ordinal of the column, rather than a value already retrieved from the database.
In the original expression:
IsDBNull(rdr.GetInt32("OrganizerID"))
GetInt32 is evaluated first. If OrganizerID contains SQL NULL, the exception is raised before IsDBNull can perform the check.
You can retrieve the column ordinal first, check whether the column contains DBNull, and only then call GetInt32:
Dim organizerOrdinal As Integer = rdr.GetOrdinal("OrganizerID")
.OrganizerID =
If(rdr.IsDBNull(organizerOrdinal),
CType(Nothing, Integer?),
CType(rdr.GetInt32(organizerOrdinal), Integer?))
The property should also be nullable if it needs to represent a database NULL:
Public Property OrganizerID As Integer?
The same pattern should be applied to any other database columns that may contain NULL. For example:
Dim eventIdOrdinal As Integer = rdr.GetOrdinal("EventID")
Dim lastUpdateOrdinal As Integer = rdr.GetOrdinal("LastUpdate")
Dim organizerOrdinal As Integer = rdr.GetOrdinal("OrganizerID")
While rdr.Read()
evnt = New MyEvent With {
.EventID =
If(rdr.IsDBNull(eventIdOrdinal),
CType(Nothing, Integer?),
CType(rdr.GetInt32(eventIdOrdinal), Integer?)),
.LastUpdate =
If(rdr.IsDBNull(lastUpdateOrdinal),
CType(Nothing, DateTime?),
CType(rdr.GetDateTime(lastUpdateOrdinal), DateTime?)),
.OrganizerID =
If(rdr.IsDBNull(organizerOrdinal),
CType(Nothing, Integer?),
CType(rdr.GetInt32(organizerOrdinal), Integer?))
}
End While
Microsoft's SqlDataReader.IsDBNull(Int32) documentation confirms that the parameter is the zero-based column ordinal and recommends calling IsDBNull before typed getters to avoid an exception.
Please try this pattern and let me know whether the exception is resolved. If you found my response helpful or informative, I would greatly appreciate it if you could share your thoughts by reacting to this answer or leaving a comment.
Thank you.