Efcore: In Global Query-filter When Filter pass as a variable filter doesn't get Updated value.

Created on 26 Aug 2020  路  4Comments  路  Source: dotnet/efcore


In Global Query-filter When Filter pass as a variable filter doesn't get Updated value.

public class ProductApiContext : DbContext
    {

        private Expression<Func<VariantAttribute, bool>> myfunc;

        public ProductApiContext(DbContextOptions<ProductApiContext> options)
            : base(options)
        {
           //This condition use for simplicity so we can test code easily, var: myfunc can become more complex according to user   
             if(IsValidUse)
            {
                myfunc = f => true;
            }
          else
            {
                myfunc = f => false;

            }

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<VariantAttribute>().HasQueryFilter(myfunc);
         }
    public DbSet<VariantAttribute> VariantAttribute { get; set; }
}

Further technical details

EF Core version:
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET Core 3.1)
Operating system:
IDE: (e.g. Visual Studio 2019 16.3)

closed-question customer-reported

Most helpful comment

@NitishGawde The old models will be purged when the cache reaches its limit. You can specify a custom limit by calling UseMemoryCache

All 4 comments

Query filters are stored on model. The way you are changing the query filter, it actually generates 2 different models. But unless you also change ModelCacheKey to generate a different model when IsValidUse flag changes it value, EF Core will use cached model so you will always get query filter which you created with first DbContext (whatever value it had for IsValidUse)

It is hard to understand what kind of filter you are trying to apply, to use it correctly,

  • You need to build different model if you really want to use altogether different model, or
  • You need to construct a different filter which can depend on a property/field on your DbContext and give desired result when you set value of it. In that case there will be only one filter but it will take different value based on DbContext states. EF Core will wire up correctly to use state from current DbContext in use.

@smitpatel Thanks I didn't know about this behavior. Now it's working. but if I generate more then one different model then all models always stay in memory (using ModelCacheKey) or delete automatically after some time or should I delete by key manually after done using a particular Model. So how to delete the Cache model by key???

@NitishGawde The old models will be purged when the cache reaches its limit. You can specify a custom limit by calling UseMemoryCache

Thanks, @ajcvickers, and @smitpatel

Was this page helpful?
0 / 5 - 0 ratings