I have the following snippet of code in my WCF web service that builds a set of where conditions according to the formatting of the values of a provided dictionary.
Instead of this:
cmd.Parameters.AddWithValue("@" + key, searchParams[key]);
you need to use something like this:
cmd.Parameters.Add("@" + key, SqlDbType.******).Value = searchParams[key];
You need to be able to somehow determine what datatype your parameters will have to be.
This can be something like:
SqlDbType.Int
for integer valuesSqlDbType.VarChar
for non-Unicode strings (don't forget the specify a length of the string!)SqlDbType.UniqueIdentifier
for GuidsUsing AddWithValue
is convenient - but it leaves it up to ADO.NET to guess the datatype, based on the value passed in. Most of the time, those guesses are pretty good - but at times, they can be off.
I would recommend that you always explicitly say what datatype you want.
If you read the documentation, you'll see that when you're using SQLCommand.Prepare, you need to use Parameters.Add and assign a datatype to each parameter. There is a good code sample in that link that will show you how to do it.