Filter all queries (trying to achieve soft delete)

后端 未结 1 1760
情书的邮戳
情书的邮戳 2020-11-27 20:56

I am trying to get to work soft delete behaviour in EF Core 2.0.

public interface ISoftDeleteModel
{
    bool IsDeleted { get; set; }
}

Cre

相关标签:
1条回答
  • 2020-11-27 21:23

    Can't test the exact API, but the general approach would be to create a constrained generic method and call it via reflection:

    public static class EFFilterExtensions
    {
        public static void SetSoftDeleteFilter(this ModelBuilder modelBuilder, Type entityType)
        {
            SetSoftDeleteFilterMethod.MakeGenericMethod(entityType)
                .Invoke(null, new object[] { modelBuilder });
        }
    
        static readonly MethodInfo SetSoftDeleteFilterMethod = typeof(EFFilterExtensions)
                   .GetMethods(BindingFlags.Public | BindingFlags.Static)
                   .Single(t => t.IsGenericMethod && t.Name == "SetSoftDeleteFilter");
    
        public static void SetSoftDeleteFilter<TEntity>(this ModelBuilder modelBuilder) 
            where TEntity : class, ISoftDeleteModel
        {
            modelBuilder.Entity<TEntity>().HasQueryFilter(x => !x.IsDeleted);
        }
    }
    

    Now you can use something like this inside your OnModelCreating:

    foreach (var type in modelBuilder.Model.GetEntityTypes())
    {
        if (typeof(ISoftDeleteModel).IsAssignableFrom(type.ClrType))
            modelBuilder.SetSoftDeleteFilter(type.ClrType);
    }
    
    0 讨论(0)
提交回复
热议问题