SHARE:

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
      builder.ToTable("Product");
   }
}

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

public IQueryable<Product> GetTopProducts()
{
   return _context.Products
   .IgnoreQueryFilters()
   .Take(50);
}

Nice isn’it ? 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: