c# – 设置批量大小时,SqlDataAdapter给出参数名称无效错误

我正在尝试批量插入/更新SqlDataAdapter.当我设置UpdateBatchSize = 1时,它可以工作,但将其设置为2会给出异常“指定的参数名称’Id’无效.”.

using (var sqlDataAdapter = new SqlDataAdapter
{
    UpdateBatchSize = 2
})
using (var connection = new SqlConnection("Data Source=server;Initial Catalog=DB;Integrated Security=True"))
using (var command = new SqlCommand("INSERT INTO Test (Id) VALUES (@Id)", connection)
{
    UpdatedRowSource = UpdateRowSource.None
})
{
    command.Parameters.Add("Id", SqlDbType.Int).SourceColumn = "Id";
    sqlDataAdapter.InsertCommand = command;

    var table = new DataTable("Test");
    table.Columns.Add("Id");
    table.Rows.Add(1);
    table.Rows.Add(2);
    sqlDataAdapter.Update(table);
}

最佳答案 在反编译SqlDataAdapter并使用堆栈跟踪之后,我来到了这一行.

if (!SqlCommandSet.SqlIdentifierParser.IsMatch(sqlParameter.ParameterName))
    throw ADP.BadParameterName(sqlParameter.ParameterName);

事实证明,通常你可以从SqlParameter名称中省略@,但是在执行这个批处理时,它需要它.很奇怪.正确的行变为

command.Parameters.Add("@Id", SqlDbType.Int).SourceColumn = "Id";
点赞