How do I Parameterize a null string with DBNull.Value clearly and quickly How do I Parameterize a null string with DBNull.Value clearly and quickly sql-server sql-server

How do I Parameterize a null string with DBNull.Value clearly and quickly


Cast either of your values to object and it will compile.

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);


You can avoid the explicit cast to object using SqlString.Null instead of DBNull.Value:

MiddleName ?? SqlString.Null

There are corresponding types for int, datetime, and so forth. Here's a code snippet with a couple more examples:

 cmd.Parameters.AddWithValue("@StartDate", StartDate ?? SqlDateTime.Null); cmd.Parameters.AddWithValue("@EndDate", EndDate ?? SqlDateTime.Null); cmd.Parameters.AddWithValue("@Month", Month ?? SqlInt16.Null); cmd.Parameters.AddWithValue("@FormatID", FormatID ?? SqlInt32.Null); cmd.Parameters.AddWithValue("@Email", Email ?? SqlString.Null); cmd.Parameters.AddWithValue("@ZIP", ZIP ?? SqlBoolean.Null);


Personally this is what I would do with an extension method (make sure this goes into a static class)

public static object GetStringOrDBNull(this string obj){    return string.IsNullOrEmpty(obj) ? DBNull.Value : (object) obj}

Then you'd have

myCmd.Parameters.Add("@MiddleName", MiddleName.GetStringOrDBNull());