Nested Transactions with MySQL and Entity Framework Core

2.9k Views Asked by At

I'm using MySQL with EF Core. I am currently using Pomelo Provider for MySQL. I need to implement Unit Of Work Pattern for transactions. I have a Service which calls two methods in repository. I am not able to implement nested transactions. This is how my method in service looks now:

    public void methodA(param)
    {
      using (TransactionScope tx = new 
        TransactionScope(TransactionScopeOption.Required))
        {
          repo1.save(data1);
          repo2.save(data2);
          tx.complete();
        }
    }

This is how save method in repo1 is implemented

    private readonly UserDbContext appDbContext;
    public repo1(UserDbContext _appDbContext)
    {
        appDbContext = _appDbContext;
    }
    public void save(User entity)
    {
        var dbset = appDbContext.Set<User>().Add(entity);
        appDbContext.SaveChanges();
    }

This is how save method in repo2 is implemented

    private readonly UserDbContext appDbContext;
    public repo2(UserDbContext _appDbContext)
    {
        appDbContext = _appDbContext;
    }
    public void save(UserRole entity)
    {
        var dbset = appDbContext.Set<UserRole>().Add(entity);
        appDbContext.SaveChanges();
    }

I am getting the following error while running method in service:

Error generated for warning 'Microsoft.EntityFrameworkCore.Database.Transaction.AmbientTransactionWarning: An ambient transaction has been detected. The current provider does not support ambient transactions. See http://go.microsoft.com/fwlink/?LinkId=800142'. This exception can be suppressed or logged by passing event ID 'RelationalEventId.AmbientTransactionWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

This is how I registered UserDbContext in Startup.cs

    services.AddDbContext<UserDbContext>(options => options.UseLazyLoadingProxies().UseMySql("Server = xxxx; Database = xxx; Uid = xx;ConnectionReset=True;", b => b.MigrationsAssembly("AssemblyName")));

I even tried adding a middleware which starts transaction at the begining of request and commits/rollbacks during the response . But still I am not able to manage nested transactions.

This is how my middleware looks:

    public class TransactionPerRequestMiddleware
    {
       private readonly RequestDelegate next_;

       public TransactionPerRequestMiddleware(RequestDelegate next)
        {
         next_ = next;
        }

       public async Task Invoke(HttpContext context, UserDbContext 
        userDbContext)
        {
           var transaction = userDbContext.Database.BeginTransaction(
           System.Data.IsolationLevel.ReadCommitted);

           await next_.Invoke(context);

           int statusCode = context.Response.StatusCode;
           if (statusCode == 200 || statusCode==302)
            {
            transaction.Commit();
            }
            else
            {
            transaction.Rollback();
            }
        }
     }

Can anyone help me please?

0

There are 0 best solutions below