如何在通用存储库 (Entity Framework) 的包含 属性 中使用软删除?

How do I use soft delete in include Property of generic repository (Entity Framework)?

我在我的项目中使用了通用存储库和 UnitOfWork 模式,并且效果很好。

我决定用软删除的概念来改变我的项目。一切都很好,但在通用存储库 IncludesProperty 中,它返回的所有记录都包含软删除记录!

正如您在下面看到的,我不知道该如何更改

query = query.Include(includeProperty)

或在

标记的 "Include" 记录中忽略我的任何代码行
IsDeleted == true

这是我的存储库:

 public virtual TEntity GetFirstBy(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet.Where(e => e.IsDeleted == false);

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty); /// this line was first section that I changed to query.Include(includeProperty).Where(q => q.IsDeleted == false); but doesn't work!
        }

        if (orderBy != null)
        {
            // orderBy(query);
            query = orderBy(query);
        }

        return query.FirstOrDefault();
    }

    public IEnumerable<TEntity> GetAll()
    {
        return dbSet.AsEnumerable().Where(e => e.IsDeleted == false);
    }

    public virtual TEntity GetByID(long id)
    {
        // return dbSet.Find(id).Where(e => e.IsDeleted == false);
        return context.Set<TEntity>().Where(e => e.IsDeleted == false).SingleOrDefault(e => e.Id == id);
    }

    public virtual void Insert(TEntity entity)
    {
        entity.CreatedTime = DateTime.Now;
        entity.IsDeleted = false;
        dbSet.Add(entity);
    }

正如@David 所说,我改变了软删除的方式,并在 OnModelCreating 中使用 Global Query Filters

modelBuilder.Entity().HasQueryFilter(p => !p.IsDeleted);

它会自动应用于涉及这些实体类型的任何 LINQ 查询,包括间接引用的实体类型,例如通过使用包含或直接导航 属性 引用。

如果我出于任何临时原因决定忽略软删除,我会简单地使用下面的 IgnoreQueryFilters

blogs = db.Blogs
.Include(b => b.Posts)
.IgnoreQueryFilters()
.ToList()