簡體   English   中英

實體框架中的批量刪除

[英]bulk delete in entity framework

我想使用linq批量刪除表中的記錄。 有一篇帖子描述了如何做到這一點: LINQ to Entities中的批量刪除

var query = from c in ctx.Customers
            where c.SalesPerson.Email == "..."
            select c;

query.Delete();

但是我的var變量中不存在“刪除”功能。
此外,我的上下文中不存在“SubmitChanges”功能。

有一個有趣的NuGet包, 可以讓你進行批量刪除和更新

實體框架中目前不支持批量刪除。 它實際上是在codeplex上討論的功能之一,現在EF是開源的。

EntityFramework.Extended提供批量刪除支持(你可以在nuget中找到它)但是我的經驗是它有一些性能問題。

此代碼為任何DbContext添加了一個簡單的擴展方法,該方法將批量刪除您提供的實體框架查詢中引用的任何表中的所有數據。 它的工作原理是簡單地提取查詢中涉及的所有表名,並嘗試通過發出“DELETE FROM tablename”SQL查詢來刪除數據,這在大多數類型的數據庫中都很常見。

要使用,只需執行以下操作:

myContext.BulkDelete(x => x.Things);

這將刪除鏈接到Things實體商店的表中的所有內容。

編碼:

using System.Linq;
using System.Text.RegularExpressions;

namespace System.Data.Entity {

    public static class DbContextExtensions {

        /// <summary>
        /// Efficiently deletes all data from any database tables used by the specified entity framework query. 
        /// </summary>
        /// <typeparam name="TContext">The DbContext Type on which to perform the delete.</typeparam>
        /// <typeparam name="TEntity">The Entity Type to which the query resolves.</typeparam>
        /// <param name="ctx">The DbContext on which to perform the delete.</param>
        /// <param name="deleteQuery">The query that references the tables you want to delete.</param>
        public static void BulkDelete<TContext, TEntity>(this TContext ctx, Func<TContext, IQueryable<TEntity>> deleteQuery) where TContext : DbContext {

            var findTables = new Regex(@"(?:FROM|JOIN)\s+(\[\w+\]\.\[\w+\])\s+AS");
            var qry = deleteQuery(ctx).ToString();

            // Get list of all tables mentioned in the query
            var tables = findTables.Matches(qry).Cast<Match>().Select(m => m.Result("$1")).Distinct().ToList();

            // Loop through all the tables, attempting to delete each one in turn
            var max = 30;
            var exception = (Exception)null;
            while (tables.Any() && max-- > 0) {

                // Get the next table
                var table = tables.First();

                try {
                    // Attempt the delete
                    ctx.Database.ExecuteSqlCommand(string.Format("DELETE FROM {0}", table));

                    // Success, so remove table from the list
                    tables.Remove(table);

                } catch (Exception ex) {
                    // Error, probably due to dependent constraint, save exception for later if needed.                    
                    exception = ex;

                    // Push the table to the back of the queue
                    tables.Remove(table);
                    tables.Add(table);
                }
            }

            // Error error has occurred, and cannot be resolved by deleting in a different 
            // order, then rethrow the exception and give up.
            if (max <= 0 && exception != null) throw exception;

        }
    }
}

我這樣做似乎工作得很好。 如果有任何原因,這是不好的做法,請告訴我們。

        var customersToDelete = await ctx.Customers.Where(c => c.Email == "...").ToListAsync();

        foreach (var customerToDelete in customersToDelete)
        {
            ctx.Customers.Remove(customerToDelete);
        }

        await ctx.SaveChangesAsync();

我在使用SaveChanges調用后執行數千個DELETE查詢時遇到了同樣的問題。 我不確定EntityFramework.Extensions商業庫會對我有所幫助所以我決定自己實現批量DELETE並提出類似於BG100解決方案的東西!

public async Task<List<TK>> BulkDeleteAsync(List<TK> ids)
{
    if (ids.Count < 1) {
        return new List<TK>();
    }

    // NOTE: DbContext here is a property of Repository Class
    // SOURCE: https://stackoverflow.com/a/9775744
    var tableName = DbContext.GetTableName<T>();
    var sql = $@"
        DELETE FROM {tableName}
        OUTPUT Deleted.Id
        // NOTE: Be aware that 'Id' column naming depends on your project conventions
        WHERE Id IN({string.Join(", ", ids)});
    ";
    return await @this.Database.SqlQuery<TK>(sql).ToListAsync();
}

如果你有像通用存儲庫這樣的東西應該適合你。 至少你可以嘗試將它融入你的EF基礎設施。

我還調整了一點,並能夠在多個實體塊上執行查詢。 如果您的數據庫中有任何查詢大小限制,它會對您有所幫助。

const int ChunkSize = 1024;
public async Task<List<TK>> BulkDeleteAsync(List<TK> ids)
{
    if (ids.Count < 1) {
        return new List<TK>();
    }
    // SOURCE: https://stackoverflow.com/a/20953521/11344051
    var chunks = ids.Chunks(ChunkSize).Select(c => c.ToList()).ToList();
    var tableName = DbContext.GetTableName<T>();

    var deletedIds = new List<TK>();
    foreach (var chunk in chunks) {
        var sql = $@"
            DELETE FROM {tableName}
            OUTPUT Deleted.Id
            WHERE Id IN({string.Join(", ", chunk)});
        ";
        deletedIds.AddRange(DbContext.Database.SqlQuery<TK>(sql).ToListAsync());
    }
    return deletedIds;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM