4

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 ?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Shadi
  • 191
  • 3
  • 13

1 Answers1

5

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

Sebastian Patten
  • 7,157
  • 4
  • 45
  • 51
Shadi
  • 191
  • 3
  • 13