IsDBNull(rdr.GetInt32("OrganizerID")) fails before IsDBNull can help, because GetInt32 is already trying to read the column as a non-null Int32. When the database value is NULL, that call throws SqlNullValueException.
Use a null check on the column value first, and only call GetInt32 when the value is not null.
In ADO.NET, database nulls are not the same as CLR nullable value types. For database ANSI SQL nulls, null handling must be done explicitly.
A correct pattern is:
While rdr.Read()
evnt = New MyEvent With {
.EventID = If(rdr.IsDBNull(rdr.GetOrdinal("EventID")), Nothing, rdr.GetInt32(rdr.GetOrdinal("EventID"))),
.LastUpdate = rdr.GetDateTime(rdr.GetOrdinal("LastUpdate")),
.OrganizerID = If(rdr.IsDBNull(rdr.GetOrdinal("OrganizerID")), Nothing, rdr.GetInt32(rdr.GetOrdinal("OrganizerID")))
}
End While
Key points:
-
NULL in SQL Server is an unknown or missing value.
- A null is not
0 and not an empty string.
- Comparisons and expressions involving null follow SQL three-valued logic.
- For database values, check for null before calling typed getters like
GetInt32 or GetDateTime.
Also verify that the target property can actually hold null:
Public Property OrganizerID As Integer?
If OrganizerID is declared as plain Integer, assigning Nothing will not represent a database null in the way intended.
The same rule applies to any nullable database column, including LastUpdate if that column can also contain NULL.