Reputation: 888
Getting this error when assigning an integer variable to a value coming back from a SQL stored procedure that may at times contain a NULL.
System.InvalidCastException: Specified cast is not valid.
Code snippet:
Dim iUserId As Nullable(Of Integer)
' Get the UserId associated to the server.
.CommandType = Data.CommandType.StoredProcedure
.CommandText = "SelectUserIdByServerId"
.Parameters.Clear()
.Parameters.AddWithValue("@ServerId", Request("serverid"))
' Returns back 1 column.
iUserId = .ExecuteScalar()
I though that if I have: Dim iUserId As Nullable(Of Integer)
, that it should not have a problem with it.
Upvotes: 1
Views: 3479
Reputation: 46909
ExecuteScalar()
returns Object
which is an integer
or DbNull
value.
So you need to write it like this:
Dim tmp As Object = .ExecuteScalar()
iUserId = if(Convert.IsDbNull(tmp), new integer?(), directcast(tmp, integer))
Upvotes: 3