Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda