Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent EF core 5 from creating a savepoint when saving

We're using EF Core within a context where we always manage the transaction externally. We also have to use MARS. This combination causes the following warning since we've upgraded to EF Core 5:

Microsoft.EntityFrameworkCore.Database.Transaction - Savepoints are disabled because Multiple Active 
Result Sets (MARS) is enabled. If 'SaveChanges' fails, then the transaction cannot be automatically 
rolled back to a known clean state. Instead, the transaction should be rolled back by the application 
before retrying 'SaveChanges'. See https://go.microsoft.com/fwlink/?linkid=2149338 for more information. 
To identify the code which triggers this warning, call 'ConfigureWarnings(w => 
w.Throw(RelationalEventId.SavepointsDisabledBecauseOfMARS))'.

I'm fine with Savepoints being disabled (at least for now), but I'm not so happy with a logmessage for every database save...

Is there a way to tell EF Core to not use this new feature?

like image 364
Robba Avatar asked Mar 02 '23 18:03

Robba


2 Answers

As it turns out the call to ConfigureWarnings as described in the error message can also be used to Ignore the message.

One thing to note however is that contrary to what the warning message says, the SavepointsDisabledBecauseOfMARS value is not part of the RelationalEventId type. Instead it's part of the SqlServerEventId type.

To ignore the warnings, the full code then becomes as follows:

ConfigureWarnings(w => 
w.Ignore(SqlServerEventId.SavepointsDisabledBecauseOfMARS))
like image 75
Robba Avatar answered May 14 '23 07:05

Robba


In addition to Robba's anwer, because you might need to know where to place this method, like me.

You need to override OnConfiguring in your DbContext class:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.ConfigureWarnings(w => w.Ignore(SqlServerEventId.SavepointsDisabledBecauseOfMARS));
}
like image 28
Wolfware Avatar answered May 14 '23 06:05

Wolfware