Global and persistent query filters for Entity Framework Core » 14 July 2023

Occasionally, you may want to apply a filter to all queries for an entity type. For example, you may want to ensure that some records are not returned in any query, such as when an entity is soft-deleted.

Now I probably should have been familiar with this, but it can be achieved easily by using the HasQueryFilter method in your OnModelCreating.

Basically, you can do something like this:

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

Yup, that’s about it, now you don’t have to hard-code filters in your EF queries or repositories. This is especially useful when you have a lot of queries, or when you have queries that are generated by EF, such as when you use Include.

You might be wondering how you can disable the filter, for example when you want to retrieve all records, including the soft-deleted ones. This can be done by using the IgnoreQueryFilters:

var posts = db.Posts
    .IgnoreQueryFilters()
    .ToList();

Pretty cool, if you ask me.