EntityFramework 6 实现软删除

准备工作

需要下载的包

  1. EntityFramework
  2. DynamicFilter

实施

接口

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

测试模型

/// 
    /// 当前模型是需要软删除的
    /// 
    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; }
    }
 /// 
    /// 不需要软删除
    /// 
    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 Products { get; set; }
public DbSet UserlessThings { get; set; }

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

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

SoftDelete函数内容

private void SoftDelete(DbEntityEntry 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的数据。

你可能感兴趣的:(EntityFramework 6 实现软删除)