Back
Close

Global query filters and soft delete with Entity Framework Core

gpeipman
2,313 views

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
·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

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants