public void BulkCopyAndSave <T>(IEnumerable <T> source, bool isDispose = false, int?batchSize = null) { var mapping = TFundSolution.Utils.EntityFramworks.EfMappingFactory.GetMappingsForContext(this.ContextCis); var currentType = typeof(T); var typeMapping = mapping.TypeMappings[typeof(T)]; var tableMapping = typeMapping.TableMappings.First(); IList <ColumnMapping> properties = tableMapping.PropertyMappings .Where(p => currentType.IsSubclassOf(p.ForEntityType) || p.ForEntityType == currentType) .Select(p => new ColumnMapping { NameInDatabase = p.ColumnName, NameOnObject = p.PropertyName }).ToList(); if (tableMapping.TPHConfiguration != null) { properties.Add(new ColumnMapping { NameInDatabase = tableMapping.TPHConfiguration.ColumnName, StaticValue = tableMapping.TPHConfiguration.Mappings[typeof(T)] }); } using (var reader = new EFDataReader <T>(source, properties)) { var connection = new Oracle.DataAccess.Client.OracleConnection(ContextCis.Database.Connection.ConnectionString); if (connection.State != System.Data.ConnectionState.Open) { connection.Open(); } using (Oracle.DataAccess.Client.OracleBulkCopy copy = new Oracle.DataAccess.Client.OracleBulkCopy(connection, Oracle.DataAccess.Client.OracleBulkCopyOptions.UseInternalTransaction)) { copy.BatchSize = Math.Min(reader.RecordsAffected, batchSize ?? 10000); //default batch size copy.BulkCopyTimeout = 3600; if (!string.IsNullOrWhiteSpace(tableMapping.Schema)) { copy.DestinationTableName = string.Format("{0}.{1}", tableMapping.Schema, tableMapping.TableName); } else { copy.DestinationTableName = tableMapping.TableName; } copy.NotifyAfter = 0; foreach (var i in Enumerable.Range(0, reader.FieldCount)) { copy.ColumnMappings.Add(i, properties[i].NameInDatabase); } var sourceTable = source.AsDataTableWithContext(this.ContextCis); copy.WriteToServer(sourceTable); copy.Close(); } if (isDispose) { this.ReNewContext(); } } }
private void InsertItems <T>(IEnumerable <T> items, string schema, string tableName, IList <ColumnMapping> properties, DbConnection storeConnection, int?batchSize) { using (var reader = new EFDataReader <T>(items, properties)) { var con = storeConnection as SqlConnection; if (con.State != System.Data.ConnectionState.Open) { con.Open(); } using (SqlBulkCopy copy = new SqlBulkCopy(con) { BulkCopyTimeout = 0 }) { copy.BatchSize = Math.Min(reader.RecordsAffected, batchSize ?? 15000); //default batch size if (!string.IsNullOrWhiteSpace(schema)) { copy.DestinationTableName = string.Format("[{0}].[{1}]", schema, tableName); } else { copy.DestinationTableName = "[" + tableName + "]"; } copy.NotifyAfter = 0; foreach (var i in Enumerable.Range(0, reader.FieldCount)) { copy.ColumnMappings.Add(i, properties[i].NameInDatabase); } copy.WriteToServer(reader); copy.Close(); } } }