Search code examples
c#databasesqlcommanddbnull

How to assign a value to sqlparameter NULL values without checking for null or 0?


The following check is needed to check for null values. is there a way i can do it directly?

 if(node.ID==0)
 {
   cmd.Parameters["@ID"].Value = DBNull.Value;
 }
  else
  {
    cmd.Parameters["@ID"].Value = node.ID;
  }

is there way we can cicumvent this check and a design by which we can avoid this repetitive check for each value? (by the way its just a logic that 0 to be interpreted as NULL for my case but am asking the same about nullable objects like string too)


Solution

  • For nullable types, I'd just use an extension method:

    public static object CoalesceNullToDBNull(this object input)
    {
        return input == null ? DBNull.Value : input;
    }
    

    Then use it as:

    cmd.Parameters["Foo"].Value = someExpression.CoalesceNullToDBNull();
    

    (You could give it a shorter name, of course.)

    That won't help for your case though, because you're trying to coalesce a non-null value to null. I would personally consider redesigning your model - use a nullable type for values which can be null, rather than using a magic number. However, you could still use a generic extension method:

    public static object CoalesceDefaultToDBNull<T>(this T input)
    {
        return EqualityComparer<T>.Default.Equals(input, default(T))
            ? DBNull.Value : (object) input;
    }
    

    That will convert 0, '\0', false, null etc to DBNull.Value. You'd have to use that with extreme care though, as I assume there are plenty of places where a 0 should really be a 0.