EF Core Global Filters

(working code inside this project)

Let’s set a case where we have the following User class where we want to soft delete it, as we want to keep deleted records.

public class User
{
	public int Id { get; set; }
	public string Name { get; set; }
	public bool Active { get; set; }
}

In many cases we don’t care about “deleted” records so most times we will filter out deleted records like this

// DON'T DO THIS
public async Task<List<User>> GetUsers()
{
	return await _context.Users.Where(user => user.Active).ToList();
}

Instead of always doing this, which is too verbose, we may use Global Query Filters. This way we apply the filter globally.

public class ApDbContext : DbContext
{
	// ... more code
	
	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		modelBuilder.Entity<User>().HasQueryFilter(user => user.Active);
	}
}

From now on, everytime we need to retrieve something from the User table, it will automatically filter out the deleted records.

Ignore global filters

In case we need to override a filter, we may retrieve all records as follows

public async Task<List<User>> GetUsersIncludingDeleted()
{
	return await _context.Users.IgnoreQueryFilters().ToList();
}

Reference(s)

https://steven-giesel.com/blogPost/a807373c-dcc6-42f9-995f-e69dcea1cd47#:~:text=Soft%20deletes%20can%20have%20a,your%20insert%20and%20update%20performance.