One of the most eagerly anticipated entity framework enhancements. You can filter the add configuration globally, which will filter every query obtained from the database using the entity framework, using the Entity Framework Global Query Filter.
By the name itself, you can realize the use of this feature. You are adding data filtration criteria on a global level. So you don’t have to write the same code condition everywhere in the project.
Let’s create a simple class in the application that includes a few properties, primarily the important filtering property called IsActive. This helps us to filter the non-active employees from the database.
using System;
using System.Collections.Generic;
using System.Text;
namespace EfCoreDemo {
public class Employee {
public int Id {
get;
set;
}
public string Name {
get;
set;
}
public int Age {
get;
set;
}
public string ContactNo {
get;
set;
}
public bool IsActive {
get;
set;
}
}
}
Suppose we want to add a query filter to the Employee entity. In that case, that should be done either in the OnModelCreating method of the DbContext or in the EntityTypeConfiguration<T> class related to entity T. For now, we could create a DbContext and override its OnModelCreating method, then configure the Author entity by telling the context to filter out soft-deleted records automatically; their IsActive property is true. Seed the Employee data to the database. In the example below, I added 4 records, with the first two as IsActive is true and the second as IsActive is false.
public partial class EmployeeContext: DbContext {
public EmployeeContext(DbContextOptions options): base(options) {}
public DbSet < Employee > Authors {
get;
set;
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity < Employee > ().HasQueryFilter(c => c.IsActive);
base.OnModelCreating(modelBuilder);
modelBuilder.Seed();
}
}
public static class ModelBuilderExtension {
public static void Seed(this ModelBuilder modelBuilder) {
modelBuilder.Entity < Employee > ().HasData(new Employee {
Id = 1, Name = "Jay", Age = 27, ContactNo = 99999999, IsActive = true
}, new Employee {
Id = 2, Name = "Krishna", Age = 26, ContactNo = 88888888, IsActive = true
}, new Employee {
Id = 3, Name = "Reddy", Age = 25, ContactNo = 88888888, IsActive = false
}, new Employee {
Id = 4, Name = "Majji", Age = 26, ContactNo = 77777777, IsActive = false
});
}
}

Jaydeep PatilPosted Mar 11, 2023, 3:04 PM
Good technique.