efcore
efcore copied to clipboard
Set isolation level globally for all EF queries/updates/etc.
I am checking online what is easiest way to set the transaction isolation level when using EF Core 6.
Some people using https://stackoverflow.com/a/59933774/960567
public class ConnectionIsolationLevelInterceptor: IDbConnectionInterceptor
{
// Have empty implementations for all unused IDbConnectionInterceptor methods
public void BeganTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext)
{
}
...
... all other unused methods
...
public void Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
command.ExecuteNonQuery();
}
}
}
Some using Migrator,
internal sealed class Configuration : DbMigrationsConfiguration<SupplierEntities>
{
public Configuration()
{
SetSqlGenerator("System.Data.SqlClient", new SqlMigrator());
}
private class SqlMigrator : SqlServerMigrationSqlGenerator
{
public override IEnumerable<MigrationStatement> Generate(
IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)
{
yield return new MigrationStatement { Sql = "set transaction isolation level read committed" };
foreach (var statement in base.Generate(migrationOperations, providerManifestToken))
yield return statement;
}
}
}
and some suggested to use base constructor,
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
}
Any guidlines from the team how can we set isolation level globally.
EF Core version: Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: (e.g. .NET 6.0) Operating system: IDE: (e.g. Visual Studio 2022 17.6)
Putting this on the backlog to support as a first-class option.
@imranbaloch The interceptor approach is probably a good way to go for now.