Best method of assigning NULL value to SqlParameter

前端 未结 7 1386
野的像风
野的像风 2021-01-07 20:53

I have a number of optional input parameters I am using in a C# class method. Since the optional syntax creates a value of \'0\' when the parameter is not used, the SQL inse

7条回答
  •  梦谈多话
    2021-01-07 21:15

    You'd need to check each parameter value and use DBNull.Value send null. We have an extension method off object to make this a little easier.

    public static class ObjectExtensions
    {
        public static object OptionalParam(this T value, T optionalValue = default(T))
        {
            return Equals(value,optionalValue) ? (object)DBNull.Value : value;
        }
    }
    

    Usage:

    var sqlInput = new SqlParameter("@itemsRead", input.OptionalParam());
    

    Or if you want to consider a non-default, arbitrary value as the default value:

    var sqlInput = new SqlParameter("@itemsRead", input.OptionalParam(-1));
    

提交回复
热议问题