dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.63k stars 3.15k forks source link

Set isolation level globally for all EF queries/updates/etc. #31442

Open imranbaloch opened 1 year ago

imranbaloch commented 1 year ago

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)

ajcvickers commented 12 months ago

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.