EntityFramework 6 实现软删除

准备工作

需要下载的包

  1. EntityFramework
  2. DynamicFilter

实施

接口

   /// <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的数据。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,167评论 2 89
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,877评论 19 139
  • 本文参加【世界华语悬疑文学大赛】征稿活动,本人承诺,文章内容为原创。 1 、探亲 秦默告诉我,我奶奶病了,想要见我...
    唐砚阅读 4,643评论 9 18
  • 朱零,现为中国美术家协会会员、中国书法家协会会员,清华美院高研班导师、北京大学中国画导师工作室(范扬、李小可)执行...
    雪莲花书画院阅读 5,572评论 0 1
  • 为嘛休息比上班还累,上班不用做太多事,说是在家休息各种收拾打扫卫生啊,抓狂。而且还得完成明天要交的材料,目前我连一...
    望飞雪阅读 1,535评论 1 2

友情链接更多精彩内容