private static BulkOperationConfig GetBulkOperationConfig <T>(BulkOperationParam <T> bulkOperationParam, string tempTableName) { var type = typeof(T); var bulkOperationConfig = new BulkOperationConfig { DestinationTableName = bulkOperationParam.TableName ?? GetTableName(type), AllProperties = PropertiesCache.TypePropertiesCache(type) }; if (bulkOperationParam.ExtraColumns != null) { var rowVersionPropertyInfo = bulkOperationConfig.AllProperties.FirstOrDefault(p => p.Name == "RowVersion"); if (rowVersionPropertyInfo != null) { bulkOperationConfig.AllProperties.Remove(rowVersionPropertyInfo); } foreach (var extraColumnsKey in bulkOperationParam.ExtraColumns.Keys) { bulkOperationConfig.AllProperties.Add(new CustomPropertyInfo(extraColumnsKey, typeof(object))); } if (rowVersionPropertyInfo != null) { bulkOperationConfig.AllProperties.Add(rowVersionPropertyInfo); } } bulkOperationConfig.AllPropertiesString = GetColumnsStringSqlServer(bulkOperationConfig.AllProperties); bulkOperationConfig.TempTable = $"##{bulkOperationConfig.DestinationTableName.Replace(".", "_").Replace("[", string.Empty).Replace("]", string.Empty)}{tempTableName}"; var columnNames = bulkOperationConfig.AllPropertiesString.Replace(", [RowVersion]", ""); var command = new SqlCommand( $@"SELECT TOP 0 {columnNames} INTO {bulkOperationConfig.TempTable} FROM {bulkOperationConfig.DestinationTableName} target WITH(NOLOCK);", bulkOperationParam.Connection as SqlConnection); if (bulkOperationParam.Connection.State != ConnectionState.Open) { bulkOperationParam.Connection.Open(); } command.ExecuteNonQuery(); var command2 = new SqlCommand($@"ALTER TABLE {bulkOperationConfig.TempTable} ADD RowVersion binary(8) NULL;", bulkOperationParam.Connection as SqlConnection); command2.ExecuteNonQuery(); return(bulkOperationConfig); }
private static void WriteToServer <T>(BulkOperationParam <T> bulkOperationParam, BulkOperationConfig config) { using (var bulkCopy = new SqlBulkCopy(bulkOperationParam.Connection as SqlConnection, SqlBulkCopyOptions.Default, bulkOperationParam.Transaction)) { bulkCopy.BulkCopyTimeout = bulkOperationParam.BulkCopyTimeout; bulkCopy.BatchSize = bulkOperationParam.BatchSize; bulkCopy.DestinationTableName = config.TempTable; bulkCopy.WriteToServer(ToDataTable(bulkOperationParam.Data, config.TempTable, config.AllProperties, bulkOperationParam.ExtraColumns).CreateDataReader()); } }