You don't need to create a new instance of it - the SqlBulkCopy class has a property which is a mapping collection that you can use:
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);
}
}
EDIT:
Based on the comments, the goal was to make a generic function, e.g. not have to hardcode the mapping explicitly in the function. Since the ColumnMappingCollection cannot be instantiated, I would recommend passing a List<string>
or similar that contains the column mapping definition into the function. For example:
var columnMapping = new List<string>();
columnMapping.Add("field1,field3");
columnMapping.Add("foo,bar");
Then re-define the function as
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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…