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
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));