i am using a SqlCommand to execute a stored procedure. The parameters are created automatically based on the definition of the stored procedure by using the DeriveParameters
method of class SqlCommandBuilder
. This automatically sets the DbType for me. Next I loop through the dictionary with <string, object>
key-value pairs where the string is the name of the parameter and the object contains its value to set.
Simplied example source:
public DataTable FetchProducts(SqlConnection sqlConn, IDictionary<string, object> paramvalues)
{
using (SqlCommand cmd = new SqlCommand("ProcFetchProducts", sqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
foreach (KeyValuePair<string, object> pair in paramvalues)
{
var index = cmd.Parameters.IndexOf(pair.Key);
cmd.Parameters[index].Value = pair.Value;
}
using (var dr = cmd.ExecuteReader())
{
var dt = new DataTable("Result");
dt.Load(dr);
return dt;
}
}
}
Sometimes the object contains a value which does not match the parameter's DBType. For instance, a parameter is of type smallint and the object contains a string. Now when I execute the datareader, I get a "input string is not in a correct format" FormatException
, which does not tell me which parameter is causing this problem.
So my main question is: is there a way to cast the object from the dictionary to the DBType defined in the parameter, so I can check if it is of the right type before executing the datareader?