EF Core global filter query by userId

Viewed 72

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));
    }
}
1 Answers

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)
    );
}
Related