In our project we use Linq2SQL, but now we need to have a possibility to quickly insert nearly 15k rows in database table, so i wrote an extension method:
public static void BulkInsertBigData(Table<Maintenance> maintenance, IEnumerable<Maintenance> maintenancesToInsert)
{
using (var copy = new SqlBulkCopy(maintenance.Context.Connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls))
{
//copy.ColumnMappings.Add("Id", "Id");
//copy.ColumnMappings.Add("FacilityId", "FacilityId");
//copy.ColumnMappings.Add("ParentFacilityId", "ParentFacilityId");
//copy.ColumnMappings.Add("StartTime", "StartTime");
//copy.ColumnMappings.Add("EndTime", "EndTime");
//copy.ColumnMappings.Add("ExpirationTime", "ExpirationTime");
//copy.ColumnMappings.Add("DispatcherUserName", "DispatcherUserName");
copy.DestinationTableName = "dbo.Maintenance";
var data = maintenancesToInsert.ToDataTable();
copy.WriteToServer(data);
}
}
Maintanance is auto-generated Linq2SQL class. This code works great when i uncomment ColumnMappings lines, but they doesn't fit, because if somebody will change dbml this code won't work(this code isn't agile :) ). ToDataTable()
is a reflection-based method, which converts List of Maintenance to DataTable.
I'll be gratefull for any help