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
?
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.
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;
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With