Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
EF Core global filter query by userId

I have situation where I would like to filter tables by logged-in userId or to be exact some field called AllowedVehicles. Thing is that identityContext has populated field AllowedVehicles only when it is logged-in and after is AllowedVehicles property actually read from database. My code doesn't work since AllowedVehicles is empty list once OnModelCreating is executed and it is executed only once.

How can I make global filter query in this case.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyGlobalFilters<IBaseEntity>(x => x.DeletedAt == null);
    if (_identityContext != null && _identityContext.AllowedVehicles.Count() > 0)
    {
        modelBuilder.ApplyGlobalFilters<Vehicle>(x => _identityContext.AllowedVehicles.Select(x => x.Id).Contains(x.Id));
    }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

OnModelCreating is called only once per DbContext class. And you do not have to expect that you may apply filter conditionally.

One solution is to define your conditions in filter:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyGlobalFilters<IBaseEntity>(x => x.DeletedAt == null);

    modelBuilder.ApplyGlobalFilters<Vehicle>(x => _identityContext == null 
        || !_identityContext.AllowedVehicles.Any() 
        || _identityContext.AllowedVehicles.Select(x => x.Id).Contains(x.Id)
    );
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!