Global query filters and soft delete with Entity Framework Core

gpeipman
11.4K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

What are global query filters?

Global query filters introduced in Entity Framework 2.0 allow us to define conditions applied automatically to entities when they are queried. This way it is possible to omit soft deleted entities or entities belonging to different tenant etc.

This example focuses on supporting soft deletes on model level using global query filters.

Let's start Person entity that has IsDeleted field.

public class Person
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsDeleted { get; set; }
}

Global query filters are defined when database context builds the model. Take also careful look at AddSampleData() method and notice that John Doe is soft deleted while others are not.

public class ExampleDbContext: DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString());
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

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

    public void AddSampleData()
    {
        People.Add(new Person { Id = 1, FirstName = "Gunnar", LastName = "Peipman", IsDeleted = false });
        People.Add(new Person { Id = 2, FirstName = "John", LastName = "Doe", IsDeleted = true });
        People.Add(new Person { Id = 3, FirstName = "Mary", LastName = "Jones", IsDeleted = false });

        SaveChanges();
    }
}

Demo

Now it's time to run the demo. This demo creates instance of database context, initializes sample data and then queries out all people. Check output and compare it to sample data shown above.

Click Run to see the demo

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content