Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable logging of DbUpdateConcurrencyException

Due to external circumstances, my application could run into a DbUpdateConcurrencyException when updating data in the database and then calling dbContext.SaveChangesAsync(). I'm handling this exception for myself by catch (DbUpdateConcurrencyException) and then reacting to this error case. Hence this error should not be handled or logged by Entity Framework.

Unfortunately, EF seems to log the error internally before my exception handler can jump in. I tried to configure the DbContext logging in Startup.cs as follows in order to prevent logging the DbUpdateConcurrencyException, but it did not help:

services.AddDbContext<IdentityDbContext>(options =>
{
    options
        .UseSqlServer(connectionString)
        .LogTo(_ => { }, new[] { CoreEventId.OptimisticConcurrencyException });
});

Obviously when Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException is thrown, it does not get the CoreEventId.OptimisticConcurrencyException event ID and hence cannot be filtered with it. Is there another way how to disable logging of the DbUpdateConcurrencyException?

like image 699
Matthias Avatar asked Sep 19 '25 08:09

Matthias


2 Answers

I posted an issue on GitHub about it and say it's a bug and there's a PR out to fix it. I think once it's done your code should work.

like image 84
Dan Avatar answered Sep 22 '25 00:09

Dan


You you can conditionally log events based on the LogLevel and eventId, eg

    optionsBuilder.UseSqlServer("Server=(LocalDb)\\MSSQLLocalDB;Database=EfCore7Test;TrustServerCertificate=true;Integrated Security=true",
        o =>
        {
            o.UseRelationalNulls();
        })
        .LogTo(m => Console.WriteLine(m), (eventId,logLevel) =>
        {
            //Console.WriteLine($"{eventId.Name} {eventId.Id}");
            if (logLevel >= LogLevel.Debug && eventId.Id != 10006) //Microsoft.EntityFrameworkCore.Update.OptimisticConcurrencyException
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        );
like image 34
David Browne - Microsoft Avatar answered Sep 22 '25 01:09

David Browne - Microsoft