I am using Entity Framework and there is a dynamic where
condition that I wish to add to all queries. Now, instead of going through all my code and adding that condition, is there some single place where I can add it, sort of like a designated function for all queries, called before they are executed?
Asked
Active
Viewed 361 times
1

abatishchev
- 98,240
- 88
- 296
- 433

pnizzle
- 6,243
- 4
- 52
- 81
-
Is this for a specific entity? Or is there a column that exists on every entity in your model that you want to add a where clause for? Also, which version of EF are you using? – devNull Apr 16 '19 at 00:43
-
@devNull Its for all entities. EF version 6 – pnizzle Apr 16 '19 at 00:51
-
Possible duplicate of [Adding Where Condition to All Requests EF6](https://stackoverflow.com/questions/41154894/adding-where-condition-to-all-requests-ef6) – devNull Apr 16 '19 at 00:55
3 Answers
1
Another option would be Global Query Filter, but it's supported only by EF Core 2.0.

abatishchev
- 98,240
- 88
- 296
- 433
1
Global Query Filters can be added so that a where clause is attached to all your queries. Basically, you just override the OnModelCreating method in your DbContext and add HasQueryFilter to the desired entities.
For further information, take a look at this resource - https://learn.microsoft.com/en-us/ef/core/querying/filters

Hristo Stoichev
- 185
- 2
- 12
0
Build queries in a separate class (e.g. query builder). Then execute it in the caller. Then wrap (decorate) the builder with another class (decorator) which will append the resulting query with the condition(s) you'd like:
interface IQueryBuilder
{
IQuerable<T> BuildQuery<T>(...);
}
class EntityFrameworkQueryBuilder : IQueryBuilder
{
public IQuerable<T> BuildQuery<T>(...) => query;
}
class PostConditionQueryBuilderDecorator : IQueryBuilder
{
ctor(IQueryBuilder builder) => _builder = builder;
public IQuerable<T> BuildQuery<T>(...) => query.Where(x => x.Foo != bar);
}
Many DI containers have first-class support for decorators.

abatishchev
- 98,240
- 88
- 296
- 433