SqlCommand.Prepare method requires all parameters to have an explicitly set type

前端 未结 2 1300
时光取名叫无心
时光取名叫无心 2021-01-18 19:40

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.

相关标签:
2条回答
  • 2021-01-18 20:35

    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 values
    • SqlDbType.VarChar for non-Unicode strings (don't forget the specify a length of the string!)
    • SqlDbType.UniqueIdentifier for Guids
      etc.

    Using 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.

    0 讨论(0)
  • 2021-01-18 20:39

    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.

    0 讨论(0)
提交回复
热议问题