如何使用实体框架自动过滤掉软删除的实体? [英] How can I automatically filter out soft deleted entities with Entity Framework?

查看:35
本文介绍了如何使用实体框架自动过滤掉软删除的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用实体​​框架代码.我覆盖 DbContext 中的 SaveChanges 以允许我执行软删除":

I am using Entity Framework Code First. I override SaveChanges in DbContext to allow me to do a "soft delete":

if (item.State == EntityState.Deleted && typeof(ISoftDelete).IsAssignableFrom(type))
{
    item.State = EntityState.Modified;
    item.Entity.GetType().GetMethod("Delete")
        .Invoke(item.Entity, null);

    continue;
}

这很好,所以对象知道如何将自己标记为软删除(在这种情况下,它只是将 IsDeleted 设置为 true).

Which is great, so the object knows how to mark itself as a soft delete (In this case it just sets IsDeleted to true).

我的问题是我怎样才能使它在我检索对象时忽略任何带有 IsDeleted 的对象?所以如果我说 _db.Users.FirstOrDefault(UserId == id) 如果那个用户有 IsDeleted == true 它会忽略它.基本上我想过滤?

My question is how can I make it such that when I retrieve the object it ignores any with IsDeleted? So if I said _db.Users.FirstOrDefault(UserId == id) if that user had IsDeleted == true it would ignore it. Essentially I want to filter?

注意:我不想只放 &&IsDeleted == true这就是为什么我用接口标记类的原因,以便删除知道如何正常工作",我想以某种方式修改检索以了解如何根据存在的接口正常工作".

Note: I do not want to just put && IsDeleted == true That's why I am marking the classes with an interface so the remove knows how to "Just Work" and I'd like to somehow modify the retrieval to know how to "Just Work" also based on that interface being present.

推荐答案

使用 EntityFramework.DynamicFilters.它允许您创建将在执行查询时自动应用(包括针对导航属性)的全局过滤器.

Use EntityFramework.DynamicFilters. It allows you to create global filters that will be applied automatically (including against navigation properties) when queries are executed.

项目页面上有一个示例IsDeleted"过滤器,如下所示:

There is an example "IsDeleted" filter on the project page that looks like this:

modelBuilder.Filter("IsDeleted", (ISoftDelete d) => d.IsDeleted, false);

该过滤器将在针对 ISoftDelete 实体的任何查询中自动注入 where 子句.过滤器在您的 DbContext.OnModelCreating() 中定义.

That filter will automatically inject a where clause on any query against an entity that is ISoftDelete. Filters are defined in your DbContext.OnModelCreating().

免责声明:我是作者.

这篇关于如何使用实体框架自动过滤掉软删除的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆