Stefan Djokic
Global
ol Tava siteStefan Djokic
Let's look at the
BOM Tayea (Uta (4
Bee mer td
Cx x)
ee ead
Bley) >a ee er aA
x.Age > 18)
-ToList();
Return all active users who have a driver's license
ix x)
eT Tee
_dbContext.Users.Where(x => x.Active &
x.HasDriverLicence)
Sr nter
Return all active users from Serbia
eee
List users =
_dbContext.Users.Where(x => x.Active &&
x.Country "Serbia')
AmeerStefan Djokic
What is common to all?
All active users
Each query, filters only users who are active. This means
aU CR Cee My ee Ca td
CCT RVC a eae Rm
Em M tm CMW Bune.
PU Lee ete me) yee la Clie
Ca UR en ema COC Cm Utd
CCS ea Rea ae Ct eC ca)
Sat
It would be great if it could be
done in one place...
be eaeStefan Djokic
Global Query Filter
With Query Filter, we can specify the same query in
Context configuration within OnModelCreating
method, globally.
protected override void OnModelCreating(ModelBuilder builder)
af
builder. Entity().HasQueryFilter(x => x.Active);
base.OnModelCreating( builder);
}
This will be applied automatically to each subsequent
query that EF sends to the database for the entity User.
Now we can remove the condition from our query
eee
List users =
_dbContext.Users.Where(x => x.Age > 18)
-ToList();Stefan Djokic
Okay, | want all inactive users.
Now what?
Le RUM C eCe Camm el
of our queries, we should use the IgnoreQueryFilters()
method.
List users =
_dbContext.Users.IgnoreQueryFilters()
-Where(x => !x.Active)
Cae ee
With this approach, we explicitly said:
Ignore all query filters created for this entity.Stefan Djokic
WANT MORE POSTS LIKE THIS?
CLICK ON THE NOTIFICATION
TAR) EA Ce) sn wy