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 ?

2
  • 1
    Yes sure Transaction.Current. Commented Nov 26, 2017 at 22:14
  • Thank you for your response @Evk, Actually I've tried it and it worked properly,Thanks in a lot. Commented Nov 27, 2017 at 18:15

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.