public static int DeleteFromQuery <T>(this IQueryable <T> querable, BulkDeleteOptions <T> options) { int rowAffected = 0; var dbQuery = querable as DbQuery <T>; var dbConnection = GetSqlConnectionFromIQuerable(querable); //Open datbase connection if (dbConnection.State == ConnectionState.Closed) { dbConnection.Open(); } using (var dbTransaction = dbConnection.BeginTransaction()) { try { var sqlQuery = SqlQuery.Parse(dbQuery.Sql); sqlQuery.ChangeToDelete("[Extent1]"); rowAffected = SqlUtil.ExecuteSql(sqlQuery.Sql, dbConnection, dbTransaction, options); dbTransaction.Commit(); } catch (Exception ex) { dbTransaction.Rollback(); throw ex; } finally { dbConnection.Close(); } } return(rowAffected); }
public static int BulkDelete <T>(this DbContext context, IEnumerable <T> entities, BulkDeleteOptions <T> options) { int rowsAffected = 0; var tableMapping = context.GetTableMapping(typeof(T)); Validate(tableMapping); var dbConnection = context.GetSqlConnection(); if (dbConnection.State == ConnectionState.Closed) { dbConnection.Open(); } using (var transaction = dbConnection.BeginTransaction()) { try { string stagingTableName = GetStagingTableName(tableMapping, options.UsePermanentTable, dbConnection); string destinationTableName = string.Format("[{0}].[{1}]", tableMapping.Schema, tableMapping.TableName); string[] storeGeneratedColumnNames = tableMapping.Columns.Where(o => o.Column.IsStoreGeneratedIdentity).Select(o => o.Column.Name).ToArray(); string deleteCondition = string.Join(" AND ", storeGeneratedColumnNames.Select(o => string.Format("s.{0}=t.{0}", o))); SqlUtil.CloneTable(destinationTableName, stagingTableName, storeGeneratedColumnNames, dbConnection, transaction); BulkInsert(entities, options, tableMapping, dbConnection, transaction, stagingTableName, storeGeneratedColumnNames, SqlBulkCopyOptions.KeepIdentity); string deleteSql = string.Format("DELETE t FROM {0} s JOIN {1} t ON {2}", stagingTableName, destinationTableName, deleteCondition); rowsAffected = SqlUtil.ExecuteSql(deleteSql, dbConnection, transaction); SqlUtil.DeleteTable(stagingTableName, dbConnection, transaction); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw ex; } finally { dbConnection.Close(); } return(rowsAffected); } }