Global query filters and soft delete with Entity Framework Core

gpeipman
1,377 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
·using System;
using System.Linq;
namespace EFCoreSoftDelete
{
class Program
{
public static void Main(string[] args)
{
using (var context = new ExampleDbContext())
{
context.AddSampleData();
var people = context.People.ToList();
foreach(var person in people)
{
Console.Write(person.FirstName);
Console.Write(" ");
Console.WriteLine(person.LastName);
}
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

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