且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实施“软删除”具有“实体框架核心”的实体; (又名EF7)?

更新时间:2022-11-04 20:24:20

免责声明:我是该项目的所有者实体框架增强版

Disclaimer: I'm the owner of the project Entity Framework Plus

正如您将在@Adem链接中看到的那样,我们的库支持查询

As you will see in @Adem link, our library supports query filtering.

您可以轻松启用/禁用全局/实例过滤器

You can easily enable/disable a global/instance filter

QueryFilterManager.Filter<Item>(q => q.Where(x => !x.IsDeleted));

Wiki: EF查询过滤器

编辑:回答子问题


想在后台解释它是如何工作的?

Care to explain how this works behind the scene?

首先,您可以全局或按实例初始化过滤器

Firstly, you can either initialize filter globally or by instance

// Filter by global configuration
QueryFilterManager.Filter<Customer>(q => q.Where(x => x.IsActive));
var ctx = new EntitiesContext();
// TIP: You can also add this line in EntitiesContext constructor instead
QueryFilterManager.InitilizeGlobalFilter(ctx);

// Filter by instance configuration
var ctx = new EntitiesContext();
ctx.Filter<Post>(MyEnum.EnumValue, q => q.Where(x => !x.IsSoftDeleted)).Disable();

在后台,该库将在上下文的每个DbSet上循环并检查是否可以使用过滤器

Under the hood, the library will loop on every DbSet of the context and checks if a filter can be applied to the generic type.

在这种情况下,库将使用过滤器从DbSet过滤原始/过滤的查询,然后修改当前内部查询以获取新的过滤条件查询。

In this case, the library will filter the original/filtered query from the DbSet using the filter then modify the current internal query for the new filtered query.

总而言之,我们更改了一些DbSet内部值以使用过滤后的查询。

In summary, we changed some DbSet internal value to use the filtered query.

代码为免费 开源,如果您想了解它的工作原理。

The code is FREE & Open Source if you want to learn about how it works.

编辑:回答子问题


@jonathan这个过滤器还会包含导航集合吗?

@jonathan will this filter included navigation collections too?

对于EF Core,由于Interceptor尚不可用,因此尚不支持。但是从EF Core 2.x开始,EF团队已经实现了全局查询过滤器,应该允许这样做。

For EF Core, it's not supported yet since Interceptor is not available yet. But starting from EF Core 2.x, the EF Team has implemented Global query filters which should allow this.