public void BulkCopy(DataTable table) { using (var connection = new SqlConnection(_connectionString)) { SqlTransaction transaction = null; connection.Open(); try { transaction = connection.BeginTransaction(); using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction)) { sqlBulkCopy.BatchSize = table.Rows.Count; sqlBulkCopy.DestinationTableName = table.TableName; sqlBulkCopy.MapColumns(table); sqlBulkCopy.WriteToServer(table); } transaction.Commit(); } catch { transaction?.Rollback(); throw; } } }
public static bool BulkInsert <T>(List <T> data, Dictionary <string, ColumnType> ColMap) { try { string DestTable = ((TableNameAttribute)typeof(T).GetCustomAttributes(true)[0]).TableName; using (_Connection = GetSQLConnection()) { if (_Connection.State == System.Data.ConnectionState.Closed) { _Connection.Open(); } SqlBulkCopy copy = new SqlBulkCopy(_Connection); copy.DestinationTableName = DestTable; copy.BulkCopyTimeout = 0; DataTable dt = data.ConvertToDatatable <T>(ColMap); copy.MapColumns(ColMap); copy.WriteToServer(dt); } } catch (Exception ex) { AppLogger.Log(ex); return(false); } return(true); }