One transaction with multiple dbcontexts

后端 未结 4 2025
心在旅途
心在旅途 2020-12-05 02:55

I am using transactions in my unit tests to roll back changes. The unit test uses a dbcontext, and the service i\'m testing uses his own. Both of them are wrapped in one tra

4条回答
  •  不知归路
    2020-12-05 03:42

    For me, using 'Enlist=false' in the config file removed the DST error, but also invalidated the transaction, DB changes were persistent even if scope scope.Complete() was not reached:

    using (var scope = new TransactionScope())  
    using (var firstContext = new db1Context()) 
    using (var secondContext = new db2Context())
    {
    // do smth with dbContexts
     scope.Complete();
    }
    

    I ended up using DbContextTransaction to solve this issue:

    using (var firstContext = new db1Context())
    using (var secondContext = new db2Context())
    using (DbContextTransaction firstContextTransaction = db1Context.Database.BeginTransaction())
    using (DbContextTransaction secondContextTransaction = db2Context.Database.BeginTransaction())
        {
        try
        {
        // do smth with dbContexts                    
        firstContextTransaction.Commit();
        secondContextTransaction.Commit();
        }
        catch (System.Exception)
        {
        firstContextTransaction?.Rollback();
        secondContextTransaction?.Rollback();
        throw;
        }
        }
    

提交回复
热议问题