Entity Framework Core 2 – Global filters on queries


Entity Framework Core 2 was released on August 14th. It brought new features.

On this article I will explain one of them : Global filters on queries

They are useful in essentially two scenarios:

  • For multitenant apps
  • For soft deletes

But they are useful for many other scenarios, like in a product list query, we want also to display anytime only products that are not free: (cost > 0)

public class ProductConfiguration : IEntityTypeConfiguration<Product>
   public TenantId {get; set;}
   public void Configure(EntityTypeBuilder<Product> builder)
      builder.HasKey(x => x.ProductID);
      builder.HasQueryFilter(o => o.Cost > 0); // non free products
      builder.HasQueryFilter(o => o.TenantId > this.TenantId ); // manage tenants products
      builder.HasQueryFilter(o => !o.IsDeleted ); // manage non deleted products with soft delete

It’s possible to ignore this filters on some queries using IgnoreQueryFilters() extension method:

public IQueryable<Product> GetTopProducts()
   return _context.Products

Nice isn’it ? 🙂