其他分享
首页 > 其他分享> > .net6 EF core 软删除,全局过滤器

.net6 EF core 软删除,全局过滤器

作者:互联网

1、新建interface

public interface ISoftDelete
{
    public bool isdeleted { get; set; }
}

2、需要使用到软删除的entity要继承这个interface
3、然后在DBContext的OnModelCreating中为每个继承了ISoftDelete的entity添加过滤器

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    foreach (var entityType in builder.Model.GetEntityTypes())
    {
        if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))
        {
            entityType.AddSoftDeleteQueryFilter();
        }
    }
}
public static class SoftDeleteQueryExtension
{
    public static void AddSoftDeleteQueryFilter(this IMutableEntityType entityData)
    {
        MethodInfo methodToCall = typeof(SoftDeleteQueryExtension).GetMethod(nameof(GetSoftDeleteFilter), BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(entityData.ClrType);
        var filter = methodToCall.Invoke(null, new object[] { });
        entityData.SetQueryFilter((LambdaExpression)filter);
    }
    private static LambdaExpression GetSoftDeleteFilter<TEntity>() where TEntity : class, ISoftDelete
    {
        Expression<Func<TEntity, bool>> filter = x => !x.isdeleted;
        return filter;
    }
}

4、重写save方法

public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
    return base.SaveChanges(acceptAllChangesOnSuccess);
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
    OnBeforeSaving();
    return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
private void OnBeforeSaving()
{
    foreach (var entry in ChangeTracker.Entries())
    {
        if (typeof(ISoftDelete).IsAssignableFrom(entry.Entity.GetType()))
        {
            switch (entry.State)
            {
                case EntityState.Deleted:
                    entry.State = EntityState.Modified;
                    entry.CurrentValues["isdeleted"] = true;
                    break;
            }
        }
    }
}

标签:core,entityType,net6,EF,filter,acceptAllChangesOnSuccess,ISoftDelete,entry,publi
来源: https://www.cnblogs.com/hwxing/p/16461184.html