Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 227
Shadi Avatar asked Oct 30 '25 03:10

Shadi


1 Answers

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

like image 157
Shadi Avatar answered Nov 01 '25 16:11

Shadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!