Filtering Data with Global Query Filters in Entity Framework

Step 1. Define Model

Start by creating your entity models as usual. These models should represent your entities and include all the properties you need. For example, let's say we have a "Product" entity:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeleted {get; set; }
}

Step 2. Configure Global Query Filter

In your DbContext class, override the OnModelCreating method. Within this method, you can configure global query filters using the Entity method and the HasQueryFilter method. Here's an example of applying a global query filter to exclude soft-deleted products:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().HasQueryFilter(p => !p.IsDeleted);
}

3. Execute Filtered Queries

Once the global query filter is configured, any query involving the Product entity will automatically have the filter applied. For example, when retrieving products, soft-deleted products will be excluded by default:

var activeProducts = dbContext.Products.ToList();

Benefits of Global Query Filters

  • Data Integrity: Ensure that all queries involving the entity adhere to the desired filtering conditions, promoting data consistency and integrity. 
  • Code Simplicity: By utilizing global query filters, you centralize the filtering logic, making your code cleaner and more maintainable. 
  • Improved Performance: Global query filters allow you to exclude unnecessary data at the database level, leading to better query performance and resource utilization. 

Conclusion

Implementing global query filters in Entity Framework provides a powerful tool for applying consistent filtering conditions to your entities. By configuring global query filters during the OnModelCreating method, you can ensure that the filters are automatically applied to all queries involving the specified entity, resulting in cleaner code and improved data integrity. Give it a try! 


Similar Articles