.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;
}
}
}
}