EFCore uses FluntApi to configure global query filters
We usually have an attribute called IsDel in the class to represent soft deletion or logical deletion. This attribute will cause us to have to .where(s=>s.IsDel== every time when performing query operations) false) is very troublesome. This problem can be solved well by configuring query filters when using efCore.
public class SysUser
{
public long Id { get; set; }
public bool IsDel { get; set; } = false;
public DateTime CreateTime { get; set; }
}
The IsDel property in our SysUser class represents our soft delete.
My own DbContext class here is called MyDbContext
public class MyDbContext:DbContext
Override the OnModelCreating method in MyDbContext to configure the query filter for the SysUser class
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity().HasQueryFilter(u => u.IsDel == false);
}
But since there will be many entity classes in our project, it is a bit bloated to write them all here.
We can create a new EntityBase folder or project (the specific method depends on personal habits), I created a new folder here.
Create a new class in the folder and implement the IEntityTypeConfiguration interface to configure the entity class
public class SysUserEntityConfig : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.HasQueryFilter(u => u.IsDel == false);
}
}
Then in the OnModelCreating method, all entity configuration classes that implement the IEntityTypeConfiguration interface are automatically applied from the assembly where the current class is located through the modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly) method.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
If you are not in the same assembly, you can use this method
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var assembly = Assembly.Load("EntityConfigurations(replace this with your actual assembly)");
modelBuilder.ApplyConfigurationsFromAssembly(assembly);
}
In this way we can implement global query filtering when using efCore.