
الـ soft delete أكتر من flag اسمه IsDeleted: الـ global query filters في EF Core
- كاتب موثّق
- EF Core 10
محتويات المقال
Cannot insert duplicate key row in object 'dbo.Customers' with unique index 'IX_Customers_Email'. وفي نفس الوقت الـ orders بتاعتها لسه بتتحسب في تقرير المبيعات، بس بتختفي من صفحة الـ order اللي بتعرض اسم العميل. وصفحة "Trash" الجديدة للأدمن، المعمولة بـ IgnoreQueryFilters()، بتعرض العملاء الممسوحين من كل الـ tenants، مش بتوع الأدمن بس.
الفكرة الغلط الشائعة
IsDeleted و global query filter، وكل حاجة تانية بتفضل شغالة زي ما هي. الـ rows الممسوحة بتختفي من الـ queries، والـ Include والـ navigations بيحترموا الـ filter، ومحدش تاني في التطبيق محتاج يعرف.
HasQueryFilter(b => !b.IsDeleted)، وهو فعلًا بيخبّي الـ rows دي من كل LINQ query على الـ type، حتى اللي بتتحمّل من خلال navigation. لكن نص الحقيقة في كلمة "كل حاجة". الـ filter بيغيّر القراية بس. أما المسح والـ constraints والـ relationships فبيشتغلوا زي ما كانوا بالظبط، ولسه فاكرين إن الـ row موجود.
اللي بيحصل فعلًا
المسح مبقاش بيعمل cascade زي ما انت متوقع
SaveChanges يحوّل الـ entries اللي حالتها Deleted لـ updates بتحط IsDeleted. لو كتبته لـ Customer بس، الـ بتاع EF لسه بيشتغل على الـ orders اللي متتبّعها: في تجربة على EF Core 10 و SQL Server LocalDB، حفظة واحدة بعتت UPDATE للعميل و DELETE لكل order متحمّل. والـ orders اللي ماتحمّلتش فضلت زي ما هي، لأن الـ cascade بتاع الداتابيز مش بيشتغل غير مع DELETE حقيقي، ومفيش واحد اتبعت.
ExecuteDeleteAsync مش بيعدّي على SaveChanges، ففي التجربة مسح العميلة فعليًا، والـ ON DELETE CASCADE مسح الـ orders بتاعتها معاها. والـ query filter كان لسه متطبق على الـ WHERE بتاعه، فمسح بس الـ rows اللي الـ filter شايفها. وصفحة الـ cascade delete في الـ docs بتقولها صريحة: لو بتعمل soft delete، ماتظبطش cascade delete جوه الداتابيز نفسها.
الـ unique indexes لسه شايفة الـ rows الممسوحة
mona@x.com، فالـ unique index رفض التسجيل الجديد زي ما شفنا فوق. والـ EF Core يقدر يعمل بـ HasFilter، في الداتابيز اللي بتدعمه، فالـ rows العايشة بس هي اللي بتتنافس على القيمة. ومع HasFilter("[IsDeleted] = 0") نفس التسجيل نجح.
الـ required navigations بتخبّي rows عايشة
INNER JOIN، والـ rows اللي الـ parent بتاعها اتفلتر بتختفي. في التجربة، Orders.CountAsync() رجّع 3 و Orders.Include(o => o.Customer) رجّع 1. والـ docs بتقترح حلين: تخلّي الـ navigation optional، أو تدّي الـ dependent filter متوافق، فالاتنين يدّوا نفس الإجابة.
الـ IgnoreQueryFilters() بيقفل كل الـ filters
&&. وساعتها IgnoreQueryFilters() بيشيل الاتنين، وده اللي خلّى صفحة الـ trash ترجّع عميل من tenant تاني في التجربة. والـ EF Core 10 ضاف named query filters، و IgnoreQueryFilters(["SoftDelete"]) بيشيل ده بس: ونفس الصفحة عرضت rows الـ tenant الحالي بس، ومعاها الممسوحة.
الحل: خلّي المسح قرار
using Microsoft.EntityFrameworkCore;public sealed class ShopDb(DbContextOptions<ShopDb> options, ITenant tenant) : DbContext(options){ public DbSet<Customer> Customers => Set<Customer>(); public DbSet<Order> Orders => Set<Order>(); protected override void OnModelCreating(ModelBuilder b) { // One unnamed filter: IgnoreQueryFilters() drops the tenant check too b.Entity<Customer>() .HasQueryFilter(c => !c.IsDeleted && c.TenantId == tenant.Id); // Deleted customers keep their email forever b.Entity<Customer>().HasIndex(c => c.Email).IsUnique(); // Orders: no filter, and ON DELETE CASCADE in the database }}using Microsoft.EntityFrameworkCore;public sealed class ShopDb(DbContextOptions<ShopDb> options, ITenant tenant) : DbContext(options){ public DbSet<Customer> Customers => Set<Customer>(); public DbSet<Order> Orders => Set<Order>(); protected override void OnModelCreating(ModelBuilder b) { b.Entity<Customer>() .HasQueryFilter("SoftDelete", c => !c.IsDeleted) .HasQueryFilter("Tenant", c => c.TenantId == tenant.Id); b.Entity<Customer>().HasIndex(c => c.Email).IsUnique() .HasFilter("[IsDeleted] = 0"); // only live rows compete // Orders disappear with their customer, loaded or not b.Entity<Order>().HasQueryFilter("SoftDelete", o => !o.IsDeleted && !o.Customer.IsDeleted); // EF cascades to tracked orders; the database never deletes them b.Entity<Customer>().HasMany(c => c.Orders).WithOne(o => o.Customer) .OnDelete(DeleteBehavior.ClientCascade); }}ClientCascade بيسيب الـ cascade شغال للـ entities المتتبّعة بس مش بيعمل cascade في الداتابيز، ففي التجربة ExecuteDeleteAsync غلط على عميل ليه orders وقع بـ foreign key error بدل ما يمسحهم في صمت. وبعدين interceptor واحد بيحوّل أي delete بيتتبعه EF لـ update:
using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Diagnostics;// Register with options.AddInterceptors(new SoftDeleteInterceptor())public sealed class SoftDeleteInterceptor : SaveChangesInterceptor{ public override ValueTask<InterceptionResult<int>> SavingChangesAsync( DbContextEventData data, InterceptionResult<int> result, CancellationToken ct = default) { // Every soft-deletable entry, including orders EF cascaded to Deleted foreach (var e in data.Context!.ChangeTracker.Entries<ISoftDelete>()) { if (e.State != EntityState.Deleted) continue; e.State = EntityState.Modified; e.Entity.IsDeleted = true; e.Entity.DeletedAt = DateTime.UtcNow; } return base.SavingChangesAsync(data, result, ct); }}UPDATE ومفيش ولا DELETE. والـ docs بتاعة الـ interceptors بتقول إن كل نقطة interception ليها method sync و async، فاعمل override لـ SavingChanges كمان لو فيه أي كود لسه بينادي SaveChanges العادية.
IsDeleted مع filter واحد | ||
|---|---|---|
Include على required navigation | ||
IgnoreQueryFilters(["SoftDelete"]) بيسيب filter الـ tenant |
تطبقها إزاي في مشروعك
اعمل لستة بكل طرق المسح دوّر على RemoveوExecuteDeleteوالـ deletes بالـ raw SQL والـ cascades في الداتابيز على الـ types اللي عليها soft delete، وخلّي كل واحد فيهم update أو hard delete مقصود.صلّح الـ schema اعمل filter على IsDeletedللـ unique indexes، وحوّل الـ relationships بتاعة الـ types دي لـClientCascade، فـ EF يفضل يعمل cascade للـ entities المتتبّعة والداتابيز عمرها ما تعمل cascade لمسح حقيقي.سمّي الـ filters على EF Core 10، افصل الـ soft delete والـ tenancy في named filters، وبدّل أي IgnoreQueryFilters()فاضية بالأسامي اللي انت قاصدها.اختبر الأطراف اكتب integration tests لإعادة استخدام قيمة unique بتاعة row ممسوح، و Includeعلى parent ممسوح، ورجوع row اتمسح.
الخلاصة
الـ global query filter بيضيف Whereلـ LINQ queries بس؛ المسح والـ constraints والـ joins مايعرفوش عنه حاجة.الـ EF لسه بيعمل cascade للمسح الحقيقي على الـ dependents المتتبّعة، و ExecuteDeleteبيعدّي من فوق أي logic جوهSaveChangesخالص.الـ unique indexes محتاجة HasFilter، وإلا الـ rows الممسوحة هتفضل ماسكة قيمها.الـ required navigations ممكن توقّع rows عايشة الـ parent بتاعها متفلتر؛ ادّي الـ dependents filter متوافق معاه. في EF Core 10 سمّي الـ filters، عشان IgnoreQueryFiltersعمره ما يقفل عزل الـ tenants بالغلط.
التعليقات (0)