我想通過參數傳遞特定數據,製作一個可用於所有批量插入的SqlBulkCopy方法。
現在我需要對其中一些進行映射。我不知道如何製作SqlBulkCopyColumnMappingCollection,因為那是我計劃傳遞映射集合併使用它。但是我不知道如何製作它。我不能成為它的新對象。
這就是我現在擁有的。如何添加它做映射把它傳遞進去?
public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize)
{
// Get the DataTable
DataTable dtInsertRows = dataTable;
using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
{
sbc.DestinationTableName = DestinationTbl;
// Number of records to be processed in one go
sbc.BatchSize = batchSize;
// Finally write to server
sbc.WriteToServer(dtInsertRows);
}
}
您不需要創建它的新實例 - SqlBulkCopy類有一個屬性,它是您可以使用的映射集合:
public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize)
{
// Get the DataTable
DataTable dtInsertRows = dataTable;
using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
{
sbc.DestinationTableName = DestinationTbl;
// Number of records to be processed in one go
sbc.BatchSize = batchSize;
// Add your column mappings here
sbc.ColumnMappings.Add("field1","field3");
sbc.ColumnMappings.Add("foo","bar");
// Finally write to server
sbc.WriteToServer(dtInsertRows);
}
}
編輯:
根據評論,目標是製作通用函數,例如,不必在函數中明確地硬編碼映射。由於無法實例化ColumnMappingCollection,我建議將包含列映射定義的List<string>
或類似函數傳遞給函數。例如:
var columnMapping = new List<string>();
columnMapping.Add("field1,field3");
columnMapping.Add("foo,bar");
然後將函數重新定義為
public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize, List<string> columnMapping)
{
// Get the DataTable
DataTable dtInsertRows = dataTable;
using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
{
sbc.DestinationTableName = DestinationTbl;
// Number of records to be processed in one go
sbc.BatchSize = batchSize;
// Add your column mappings here
foreach(var mapping in columnMapping)
{
var split = mapping.Split(new[] { ',' });
sbc.ColumnMappings.Add(split.First(), split.Last());
}
// Finally write to server
sbc.WriteToServer(dtInsertRows);
}
}