SqlCommand.Prepare方法需要的所有参数有一个明确设置类型(SqlCommand.Pr

2019-06-27 00:36发布

我有下面的代码片段在构建根据提供的字典的值的格式一套那里的条件我的WCF web服务。

public static Dictionary<string, string>[] VehicleSearch(Dictionary<string, string> searchParams, int maxResults)
{
    string condition = "";
    foreach (string key in searchParams.Keys)
    {
        //Split out the conditional in case multiple options have been set (i.e. SUB;OLDS;TOY)
        string[] parameters = searchParams[key].Split(';');
        if (parameters.Length == 1)
        {
            //If a single condition (no choice list) check for wildcards and use a LIKE if necessary
            string predicate = parameters[0].Contains('%') ? " AND {0} LIKE @{0}" : " AND {0} = @{0}";
            condition += String.Format(predicate, key);
        }
        else
        {
            //If a choice list, split out query into an IN condition
            condition += string.Format(" AND {0} IN({1})", key, string.Join(", ", parameters));
        }
    }

    SqlCommand cmd = new SqlCommand(String.Format(VEHICLE_QUERY, maxResults, condition));
    foreach (string key in searchParams.Keys)
        cmd.Parameters.AddWithValue("@" + key, searchParams[key]);
    cmd.Prepare();

请注意,在字典中的值显式设置为字符串,它们被送进唯一项目AddWithValue语句。 这会产生这样的SQL:

SELECT TOP 200 MVINumber AS MVINumber
    , LicensePlateNumber
    , VIN
    , VehicleYear
    , MakeG
    , ModelG
    , Color
    , Color2
FROM [Vehicle_Description_v]
WHERE 1=1 AND VIN LIKE @VIN

和错误出来说,

System.InvalidOperationException:SqlCommand.Prepare方法需要的所有参数有一个明确设置类型。

所有的搜索,我已经做了说,我要告诉AddWithValue说我准备值的类型,但我所有的准备值是字符串,我见过的所有的例子,当他们在处理不进行任何额外的东西字符串。 我在想什么?

Answer 1:

取而代之的是:

cmd.Parameters.AddWithValue("@" + key, searchParams[key]);

你需要使用这样的事情:

cmd.Parameters.Add("@" + key, SqlDbType.******).Value = searchParams[key];

你必须能够以某种方式确定哪些数据类型的参数必须是。

这可以是这样的:

  • SqlDbType.Int整数值
  • SqlDbType.VarChar非Unicode字符串(不要忘了指定的字符串的长度 !)
  • SqlDbType.UniqueIdentifier对的GUID
    等等

使用AddWithValue是方便-但它留下高达ADO.NET猜测数据类型的基础上,传递的价值大多数时候,这些猜测都还不错-但有时,他们可以关闭。

我建议您始终明确说你想要的数据类型。



Answer 2:

如果你读了文件 ,你会看到,当你使用SQLCommand.Prepare,你需要使用Parameters.Add和数据类型分配给每个参数。 有一个在该链接会告诉你如何做到这一点的好代码示例。



文章来源: SqlCommand.Prepare method requires all parameters to have an explicitly set type