Recently, we ran into the following issue:
In a nutshell: myCommand.Parameters.AddWithValue("@SomeParameter", DBNull.Value);
apparently "types" the DBNull parameter as an nvarchar, which can be implicitly converted to almost all other types, but, unfortunately, not varbinary
, yielding the following error:
Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
Unfortunately, the solutions suggested in the linked question do not apply, since we use AddWithValue
deep inside a data access library which is designed to infer the data type from the parameter type and does not support adding the "real" SQL Server type.
I "fixed" this issue by explicitly typing DBNull parameters as int
s instead:
void MyImprovedAddWithValue(SqlCommand cmd, string key, object value)
{
if (value == DBNull.Value)
{
cmd.Parameters.Add(key, SqlDbType.Int).Value = DBNull.Value;
}
else
{
cmd.Parameters.AddWithValue(key, value);
}
}
This seems to work. Apparently, NULL typed as int can be implicitly converted to any other type supported by SQL Server.
Ignoring the fact that AddWithValue has some well-known shortcomings (which we are perfectly aware of), are there any problems to be expected by using this approach? Did the designers of SqlParameterCollection.AddWithValue
have a good reason not to do this "by default" which I am overlooking?