Search code examples
c#asp.net-coreentity-framework-coreserilog

How to Suppress Specific Global Query Filter Warnings in Serilog for EF Core?


I am using Serilog for logging in my ASP.NET Core application and encountering warnings related to global query filters in Entity Framework Core. I have applied a HasQueryFilter to exclude soft-deleted entities, like so:

builder.HasQueryFilter(e => !e.IsDeleted);

However, this is generating warnings in the logs, such as:

[23:25:24 WRN] Entity 'Account' has a global query filter defined and is the required end of a relationship with the entity 'AccountRole'. This may lead to unexpected results when the required entity is filtered out.

I want to suppress these specific warnings related to global query filters while still retaining other EF Core warnings and errors. How can I configure Serilog to filter out only these warnings without affecting other log levels or messages?


Solution

  • You can try using Serilog.Filters.Expressions package and do something like the following:

    var @event = CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning;
    
    var logger = new LoggerConfiguration()
        // ...
        .Filter
            .ByExcluding($"EventId.Id = {@event.Id} and EventId.Name = '{@event.Name}'")
        .CreateLogger();
    

    But arguably it would be better done on the EF Core side during setup via ConfigureWarnings call:

    services.AddDbContextFactory<YourContext>(o => 
        o.Use...(...) // your DB setup i.e. UseSqlite etc.
            .ConfigureWarnings(builder =>
            {
                builder.Ignore(CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning);
            }));
    

    But probably even better would be to configure the query filter for the depended entity (assuming your entities here):

    modelBuilder.Entity<Account>()
        .HasQueryFilter(a => !a.IsDeleted);    
    modelBuilder.Entity<AccountRole>()
        .HasQueryFilter(a => !a.Account.IsDeleted);