LindDotNetCore~ISoftDelete软删除接口

回到目录

概念

ISoftDelete即软删除,数据在进行delete后不会从数据库清除,而只是标记一个状态,在业务范围里都不能获取到这个数据,这在ORM框架里还是比较容易实现的,对传统的ado来说需要对sql统一进行拦截和条件过滤.

实施步骤

  1. 实体继承ISoftDelete
  2. 数据上下文实现对IsDeleted的过滤
  3. 对删除方法进行调整,添加对ISoftDelete的支持

代码实现

1 实体继承ISoftDelete

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        // 1. Add the IsDeleted property
        entityType.GetOrAddProperty("IsDeleted", typeof(bool));

        // 2. Create the query filter
        var parameter = Expression.Parameter(entityType.ClrType);

        // 3. EF.Property<bool>(post, "IsDeleted")
        var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
        var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted"));

        // 4. EF.Property<bool>(post, "IsDeleted") == false
        BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false));

        // 5. post => EF.Property<bool>(post, "IsDeleted") == false
        var lambda = Expression.Lambda(compareExpression, parameter);

        modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambda);

2 数据上下文实现对IsDeleted的过滤

public class ProductInfo : EntityBase, ISoftDelete
{
    public string Title { get; set; }
    public decimal Amount { get; set; }
    public int Discount { get; set; }
    public int Inventory { get; set; }
    public DateTime DeletedDate { get; set; }
    public string DeletedUser { get; set; }
    public bool IsDeleted { get; set; }

    /// <summary>
    /// domain method
    /// </summary>
    /// <returns></returns>
    public decimal GetSaleAmount()
    {
        return Amount * Discount / 100;
    }
}

3 对删除方法进行调整,添加对ISoftDelete的支持

代码来自Lind.DotNetCore.Repository.EFRepository类型

public void Delete(TEntity item)
{
    if (item != null)
    {
        if (typeof(ISoftDelete).IsAssignableFrom(item.GetType()))
        {
            Db.Entry(item).State = EntityState.Modified;
            var delEntity = item as ISoftDelete;
            delEntity.DeletedDate = DateTime.Now;
            delEntity.IsDeleted = true;
        }
        else
        {
            //物理删除
            Db.Set<TEntity>().Attach(item as TEntity);
            Db.Entry(item).State = EntityState.Deleted;
            Db.Set<TEntity>().Remove(item as TEntity);
        }
        this.SaveChanges();
    }
}

上面几行代码实现了对软删除的完整支持,从ISoftDelete接口到数据上下文里的过滤IsDeleted,再到优化后的Delete()方法,一切看上去都很优雅!

对于软删除支持的框架也很多,像abp,eshopconationer,linddotnetcore等!

欢迎大家的阅读与思考!

 回到目录

posted @ 2018-02-28 14:52 张占岭 阅读(...) 评论(...) 编辑 收藏