What In The Dbnull
I have a stored procedure which has a parameter that is nullable to a decimal column. The method I wrote expects a Dictionary to pass the parameter name and t
Solution 1:
I think you will have to get each value from the Dictionary and then use code like that shown below before passing the parameter to the command. In other words, store null as the value in the Dictionary, not DBNull, then call the code below to convert from null to DBNull.Value.
SqlParameterfirstNameParam=newSqlParameter("FirstName", System.Data.SqlDbType.NVarChar);
stringfirstNameValue=null; // this is the value from the Dictionaryif (firstNameValue == null) {
firstNameParam.Value = DBNull.Value;
}
else {
firstNameParam.Value = firstNameValue;
}
After refactoring, you could do something like this:
publicstaticobjectToDBNull(objectvalue) {
if (value == null) {
return DBNull.Value;
}
else {
returnvalue;
}
}
Then call ToDBNull function like this:
cmd.Parameters.AddWithValue("FirstName", ToDBNull(firstNameValue));
Solution 2:
If you have Dictionary<string, string>, and you have a value in the dictionary such that:
var dictionary = new Dictionary<string, string>() { { "hello", null } };
string data = dictionary["hello"];
var dec = data == null ? (decimal?)null : Convert.ToDecimal(data);
You could write a little extension method to make things easier for passing it to a command
publicstaticobjectValueOrDbNull(thisdecimal? value)
{
if (value.HasValue)
{
returnvalue;
}
return DBNull.Value;
}
And then add it to your command as such:
command.Parameters.Add("@your_proc_param", dec.ValueOrDbNull());
There shouldn't be any issues passing it to a procedure in this manner, since you said it's declared as a nullable decimal field.
Post a Comment for "What In The Dbnull"