Home > OS >  Apply EF global query filter in an async way
Apply EF global query filter in an async way

Time:11-25

I need to apply a global query filter in my EF DbContext.

The value to check against is retrieved by an async operation.

So something like this.

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

        modelBuilder.Entity<User>().HasQueryFilter(async u => u.CustomerId == await GetIdAsync());
    }

Of course this doesn't work, as HasQueryFilter expects a different lamda expression.

And I guess, that adding async to the OnModelCreating will bring me into troubles, too.

    protected override async void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        var id = await GetIdAsync();
        modelBuilder.Entity<User>().HasQueryFilter(u => u.CustomerId == id);
    }

Any ideas, how to solve this?

CodePudding user response:

Define property CustomerId in your DbContext:

public class MyDbContext: DbContext
{
    public int? CustomerId { get; set; }

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

        modelBuilder.Entity<User>().HasQueryFilter(u => CustomerId == null || u.CustomerId == CustomerId);
    }
}

Assign property in controller call:

context.CustomerId = await context.GetIdAsync();

And then you can sefely use Query Filter.

  • Related