20.07.2021

Global Query Filter

Entity Framework Core allows you to apply a LINQ query predicate to an Entity Type.
This is usually set up in the "OnModelCreating".
The query predicate is a Boolean expression and Entity Framework Core applies the filter automatically to a LINQ query.
A good example would be to add a field "IsDeleted" to an Entity and automatically filter the deleted entries.

 

Here's an example:

 

Entity:


public class Person
{
public Guid PersonId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public bool IsDeleted { get; set; }
}

 

Configure the query filter in the "OnModelCreating":



modelBuilder.Entity<Person>().HasQueryFilter(p => !p.IsDeleted);

    
This query retrieves all persons that are not deleted:



var filteredPersons = db.Person.ToList();
 

It is also possible to ignore this filter at runtime.
This code returns all persons:



var persons = db.Person.IgnoreQueryFilters().ToList();
 

Currently, it is only possible to configure one query filter per Entity.
However, it is possible to define more conditions in the filter, using the AND operator.

 

Advantages:   

  •  The logic is centralised in the query filter instead of being added to every query
  •  Avoids the possibility of forgetting a filter on a new query
  •  Improves code readability