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
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;
}
}