为什么这个 SqlParameterCollection 调用会抛出错误?

Why this SqlParameterCollection call is throwing error?

这是调用存储过程的代码示例。第二个进程在运行时抛出 InvalidCastException。我正在尝试将新的 SqlParameter 添加到 SqlParametersCollection 中。我见过很多使用相同语法的示例。

using (SqlCommand db = new SqlCommand("[StoredProcedureName]"))
{
    db.CommandType = CommandType.StoredProcedure;
    db.Connection = new SqlConnection(WebConfigurationAccess.ConnectionString);

    //1) works but this is long so wanted to try shortcut
    db.Parameters.Add(new SqlParameter("@pID", SqlDbType.Int));
    db.Parameters["@pID"].Value = 12345;
    //2) <<>>throws InvalidCastExpception. Id is set up as Int32
    db.Parameters.Add(new SqlParameter("@pID", SqlDbType.Int).Value = 12345);
    //3)but following codes does the job
    db.Parameters.Add("@pID", SqlDbType.Int).Value = 12345;
    db.Connection.Open();
    var dr = db.ExecuteReader();
}

我怀疑您还没有看到确切的语法。看看你得到了什么:

db.Parameters.Add(new SqlParameter("@pID", SqlDbType.Int).Value = 12345);

那是用 int 参数调用 db.Parameters.Add。我怀疑你实际上看到的是:

db.Parameters.Add(new SqlParameter("@pID", SqlDbType.Int)).Value = 12345;

或者更简单地说:

db.Parameters.Add("@pID", SqlDbType.Int).Value = 12345;

在这两种情况下,int 用于在参数上设置 Value 属性添加到 collection.

你的代码之所以能编译,是因为有一个 SqlParameterCollection.Add(object) 重载——据我所知,基本上不应该使用它。