Disable global query filters *inside* another global query filter

Viewed 130

Currently using EF Core 3.1 (although upgrading to EF Core 5 soon, so if this becomes easier in that version, I'm still interested).

I'm implementing some global query filters to restrict access to entity data based on various criteria.

One of the filters operates on a type called "Encounter". An Encounter is linked to a single Person (via foreign key PersonID), but a Person can have many Encounters. The Person record has a navigation property to all linked encounters via Person.Encounters.

The query filter for Encounter is to restrict records based on the value of a particular property on Encounter (call it EncounterType). This works fine if my query filter is something like this:

x => x.EncounterType == "MyType"

However, I need to extend this logic so that an Encounter is allowed/loaded if any encounter linked to the Person meets the criteria.

So, the query filter for Encounter needs to be something like this:

x => x.Person.Encounters.Any(y => y.EncounterType == "MyType")

This does not currently work, because we run into a cycle and a StackOverflowException1; the global query filter for Encounter ends up expanding itself infinitely. (I think it's because we access the Person.Encounters navigation property and evaluate the same Encounter query filter for each encounter in Person.Encounters.)

What I really want to do is to completely disable the global query filter for any navigation properties used in this particular expression. In this scenario, I want to consider all other Encounters linked to the Person, without further filtering.

I know when actually running a query, I can call IgnoreQueryFilters(). I want something like that, but available inside the expression or when adding the query filter with HasQueryFilter().

Is this possible? Is there any other way I can accomplish this with global query filters?


[1] Which, while frustrating, is pretty cool for me...I've never posted a question about an actual stack overflow on StackOverflow :)

0 Answers
Related