Search code examples
c#entity-frameworktransactionstransactionscope

Entity Framework :Using Transaction Scope how to check whether DbContext has transaction?


As mentioned here using Entity Framework 6 if we begin a transaction using Database.BeginTransaction() we can check whether a context has a transaction using this statement:

var transaction = db.Database.CurrentTransaction;

Unfortunately this way is not working if we used TrasctionScope to begin transaction :

var transactionScope = new TransactionScope();

I'm just wondering if there is any way to check whether a context has a transaction when I'm using TrasctionScope ?


Solution

  • Using entity framework 6 you can use transactions in two ways:

    • The first way, using Database.BeginTransaction() method:

         using (var context = new Context())
           {
               using (var dbContextTransaction = context.Database.BeginTransaction())
               {
                   try
                   {
                       //Some EF Statments
      
                       Context.SaveChanges();
                       dbContextTransaction.Commit();
      
                   }
                   catch (Exception)
                   {
                       dbContextTransaction.Rollback();
                   }
               }
      
    • The second way, using TransactionScope :

           using (var scope = new TransactionScope())
           {
               //Some EF Statments
               Context.SaveChanges();
               scope.Complete();
           }
      
    • If you used first way you can get transaction instance using statement:

      `var transaction = context.Database.CurrentTransaction;`
      
    • On the other hand if you begin transaction using TrasctionScope you have to use:

      var transaction = System.Transactions.Transaction.Current; to get transaction instance or check whether a context has a transaction or not