private void BulkCopyData(SqlTransaction transaction, List <string> tablesToCopy) { // https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlbulkcopy if (transaction is null) { throw new ArgumentNullException(nameof(transaction)); } if (tablesToCopy is null) { throw new ArgumentNullException(nameof(tablesToCopy)); } using (var sourceSqlConnection = new SqlConnection(_sourceConnectionString)) { if (!sourceSqlConnection.State.HasFlag(ConnectionState.Open)) { sourceSqlConnection.Open(); } foreach (var table in tablesToCopy) { _aggregateLogger.LogDebug($"\tSyncing table: {table}"); using (var commandSourceData = new SqlCommand($"SELECT * FROM {table} ORDER BY [Id]", sourceSqlConnection)) { using (var reader = commandSourceData.ExecuteReader()) { using (var bulkCopy = new SqlBulkCopy(transaction.Connection, _bulkCopyOptions, transaction)) { bulkCopy.DestinationTableName = table; bulkCopy.WriteToServer(reader); } } } } } }