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

To check for zero values, the following check is required. is there any way i can do this directly?

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

Is there any way that we can verify this validation and design with which we can avoid this duplicate validation for each value? (by the way, this is just logic, which 0 should be interpreted as NULL for my case, but I ask the same thing about null objects like a string)

+3
source share
4 answers

For types with a null value, I just use the extension method:

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

Then use it like:

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

(Of course, you could call it shorter.)

, null. - , , . :

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

0, '\0', false, null .. DBNull.Value. , , , , 0 0.

+4

?:

cmd.Parameters["@ID"].Value = node.ID == 0 ? (object)DBNull.Value : node.ID;
+5

, .

:

// ...
SetFormattedValue(ref cmd, node.ID);
// ...

private void SetFormattedValue(ref IDBCommand cmd, int id) // IDBCommand - or whatever your command type is
{
    if(node.ID==0)
    {
        cmd.Parameters["@ID"].Value = DBNull.Value;
    }
    else
    {
        cmd.Parameters["@ID"].Value = node.ID;
    }
}
0

??:

cmd.Parameters["@ID"].Value = node.ID ?? (object)DBNull.Value
0

All Articles