I've written a bunch of generic C# helper functions as a base for my SQL queries. All null
object parameters are converted to a DBNull.Value
. But when the target column is a varbinary
, it tells me that string
type is not compatible with the binary
one and I must convert.
Why do I need to SqlDbType
a DBNull.Value
in C#? And is there any generic way to go around this?
// works for nvarchar but throws for varbinary columns
// notice the lack of SqlDbType as I don't know it for a null object
var param1 = new SqlParameter();
param1.Name = "@Param1";
param1.Value = DBNull.Value;
It's a null... it needs no type. SQL server knows the null's type. In SQL you say [Column] IS NULL
not [Column] IS TYPE NULL
. So null is untyped. And the target column is resolved from the query not the SqlDbType
.
I just find this very unintuitive (explicitly typing nulls). I'm wondering if I'm missing something...
Code is like this:
SqlCommand CreateCommand(string query, params object[] arguments) { ... }
// in here I walk the parameters and build the proper SqlParameter for them.
// this saves me from setting up the SqlParameters by hand.
PS: String = NVarChar and Binary means VarBinary. Seriously... PPS: Not interested in EF or anything of the like.