EntityFramework 6 实现软删除 全局过滤

准备工作

需要下载的包

  1. EntityFramework
  2. EntityFramework.DynamicFilters

实施

接口

   /// <summary>
    /// 软删除要实现的接口
    /// </summary>
    public interface IDeletionWare
    {
        /// <summary>
        /// 是否已删除
        /// </summary>
        bool IsDeleted { get; set; }
        /// <summary>
        /// 删除者id
        /// </summary>
        int? DeleterId { get; set; }
        /// <summary>
        /// 删除者姓名
        /// </summary>
        string DeleterName { get; set; }
        /// <summary>
        /// 删除时间
        /// </summary>
        DateTime? DeletionTime { get; set; }
    }

测试模型

/// <summary>
    /// 当前模型是需要软删除的
    /// </summary>
    public class Product: IDeletionWare
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? DeleterId {get; set;}
        public string DeleterName {get; set;}
        public DateTime? DeletionTime {get; set;}
        public bool IsDeleted { get; set; }
    }
 /// <summary>
    /// 不需要软删除
    /// </summary>
    public class UselessThing
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

模拟session的类

public class Session
    {
        public static Session Current;

        static Session()
        {
            Current = new Session() {
                UserId = 1,
                Username = "神"
            };
        }

        public int UserId { get; set; }
        public string Username { get; set; }
    }

准备创建DbContext

首先加入两个测试属性

public DbSet<Product> Products { get; set; }
public DbSet<UselessThing> UserlessThings { get; set; }

重写SaveChanges, 这一步是执行软删除操作逻辑的

public override int SaveChanges()
{
    // 筛选出实现IDeletionWare的模型
    ChangeTracker.Entries<IDeletionWare>().ToList().ForEach(u =>SoftDelete(u));
    return base.SaveChanges();
}

SoftDelete函数内容

private void SoftDelete(DbEntityEntry<IDeletionWare> entry)
{
    /// 判断当前模型执行的操作
    switch (entry.State)
    {
        // 防止模型字段被污染
        case EntityState.Added:
            entry.Property(u => u.IsDeleted).CurrentValue = false;
            entry.Property(u=>u.DeletionTime).CurrentValue = null;
            entry.Property(u=>u.DeleterName).CurrentValue = null;
            entry.Property(u=>u.DeleterId).CurrentValue = null;
            break;
        // 防止模型字段被污染
        case EntityState.Modified:
            entry.Property(u=>u.DeleterId).IsModified = false;
            entry.Property(u=>u.DeleterName).IsModified = false;
            entry.Property(u=>u.IsDeleted).IsModified = false;
            entry.Property(u=>u.DeletionTime).IsModified = false;
            break;
        case EntityState.Deleted:
            // 阻止默认删除操作
            entry.State = EntityState.Unchanged;

            entry.Property(u=>u.DeleterId).IsModified = true;
            entry.Property(u=>u.DeleterName).IsModified = true;
            entry.Property(u=>u.IsDeleted).IsModified = true;
            entry.Property(u=>u.DeletionTime).IsModified = true;


            entry.Property(u=>u.IsDeleted).CurrentValue = true;
            entry.Property(u=>u.DeletionTime).CurrentValue = DateTime.Now;
            // 取出当前会话中的人员信息
            entry.Property(u=>u.DeleterName).CurrentValue = Session.Current.Username;
            entry.Property(u=>u.DeleterId).CurrentValue = Session.Current.UserId;
            break;
        default:
            break;
    }
}

重写OnModelCreating,添加filter, 这一步是为了添加一个能在查询时过滤软删除的数据的filter。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Filter("IsDeleted", (IDeletionWare d)=>d.IsDeleted, false);
}

测试

创建dbContext对象, 并启用刚才添加的filter

var context = new TestDbContext();
context.EnableFilter("IsDeleted");

添加测试数据

var product = new Product
{
    Name = "肥宅快乐水"
};
var uselessThing = new UselessThing
{
    Name = "..."
};

context.Products.Add(product);
context.UserlessThings.Add(uselessThing);
context.SaveChanges();

结果

 

2018_08_18_17_59.25.jpg

2018_08_18_17_59.37.jpg

删除测试数据

var product = new Product { Id = 3 };
context.Products.Attach(product);
context.Products.Remove(product);
var thing = new UselessThing { Id = 3 };
context.UselessThings.Attach(thing);
context.UselessThings.Remove(thing);
context.SaveChanges();

结果

 

2018_08_18_18_00.52.jpg

2018_08_18_18_01.03.jpg

可以看出Products的数据还在,只不过IsDeleted变为true, 而UselessThings的数据被删除了。

查询Products的数据,看能不能查到

var a = context.Products.Where(u => u.Id == 3).FirstOrDefault();

结果

 

2018_08_18_18_03.47.jpg

可以看出filter起了作用,无法查到IsDeleted为true的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值