尝试将数据插入到SQL Server表时出现错误

时间:2018-09-06 09:32:33

标签: c# asp.net .net sql-server

我正在尝试使用以下方法将数据插入到临时表中:

public void InsertPayloadtoStaging(List<CustomPayload> payLoads, int batchId)
{
    try
    {
        string agentName = appSettings.AgentName;
        var tableName = string.Empty;

        DataTable payLoadData = new DataTable();
        DataColumn idcolumn = new DataColumn("Id", typeof(string));
        payLoadData.Columns.Add(idcolumn);

        DataColumn payLoadcolumn = new DataColumn("Payload", typeof(string));
        payLoadData.Columns.Add(payLoadcolumn);

        DataColumn scheduleIdcolumn = new DataColumn("BatchId", typeof(int));
        payLoadData.Columns.Add(scheduleIdcolumn);

        foreach (AgentPayload payLoad in payLoads)
        {
            DataRow dr = payLoadData.NewRow();

            dr["Id"] = payLoad.Id;
            dr["Payload"] = payLoad.Payload;
            dr["BatchId"] = batchId;

            payLoadData.Rows.Add(dr);
        }

        switch (agentName)
        {
            case Constants.Agent1:
                tableName = _configuration.appSettings.Agent1_StagingTable;
                break;
            case Constants.Agent2:
                tableName = _configuration.appSettings.Agent2_StagingTable;
                break;
            case Constants.Agent3:
                tableName = _configuration.appSettings.Agent3_StagingTable;
                break;
            case Constants.Agent4:
                tableName = _configuration.appSettings.Agent4_StagingTable;
                break;
            default:
                break;
        }

        this._connection.Open();

        using (SqlBulkCopy s = new SqlBulkCopy(this._connection))
        {
            s.DestinationTableName = tableName;
            s.BulkCopyTimeout = 0;
            s.BatchSize = _configuration.appSettings.AgentPayloadBatchSize;

            foreach (var column in payLoadData.Columns)
                s.ColumnMappings.Add(column.ToString(), column.ToString());

            DataTableReader reader = payLoadData.CreateDataReader();

            s.WriteToServer(reader);
        }

        this._connection.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

列表包含一个ID,后跟一个JSON字符串。

我按如下方式调用此方法:

InsertPayloadtoStaging(agentPayLoads, _batchId);

调用该方法后,出现以下错误:

  

指定的参数超出有效值范围。
  参数名称:DestinationTableName

我不确定为什么在按预期传递参数时出现此错误。我什至对代码进行了单元测试,并且运行良好。仅当我从其他方法调用此错误时,才给出此错误。

0 个答案:

没有答案