Entity Framework Core 3.0: Modify configured Global Query during runtime

Viewed 1328

I've following requirement:

During the model configuration, I create a QueryFilter for an Entity

var entity = modelBuilder.Entity<TBaseTable>().HasQueryFilter(r => r.UserId == CurrentUserId)

So during runtime in some cases the CurrentUserId changes. But my QueryFilter does not get refreshed. The filter criteria still are working with the old UserId value, which I had during the configuration. How do i modify the my QueryFiler, which was set during the configuration? If I'm right then the whole model is already cached and will not be reinitialized. Any ideas about that?

1 Answers

The trick is to declare CurrentUserId as a property on your DbContext class - the property getter can still return a value from a global class instance.

Global filters can be made dynamic by using properties/methods/fields of the db context. See the TenantId example in Global Query Filters documentation.

(Since I needed to read the comments to find the answer to your question I rephrased the comment as provided by "Ivan Stoev Oct 8 '19 at 15:34" and posted it as an answer)

Related