chana
chana

Reputation: 241

Get the transaction id when the transaction is committed

I am using IEnlistmentNotification interface from transaction scope and I want to access the current transaction id in the commit method after the scope is completed like this:

public void Commit(Enlistment enlistment)
{     
    string transactionId = Transaction.Current.TransactionInformation.LocalIdentifier;
    enlistment.Done();
} 

But I am getting an error because now the transaction.current is null. From what I check the enlistment instance has private member of the transactionId, but I can't access it for his protection level.

Is there another way to get the transaction id when the scope is completed?

Upvotes: 1

Views: 2232

Answers (1)

Bart De Boeck
Bart De Boeck

Reputation: 806

        using (TransactionScope scope = new TransactionScope())
        {
            using (YourContext context = new YourContext())
            {
                //DB operations
                context.SaveChanges();
            }
            Transaction.Current.TransactionCompleted += Current_TransactionCompleted;
            TransactionInformation info = Transaction.Current.TransactionInformation;
            string transactionId = Guid.Empty.Equals(info.DistributedIdentifier) ? info.LocalIdentifier : info.DistributedIdentifier.ToString();
            scope.Complete();
        }

        //For the transaction completed event:
        private void Current_TransactionCompleted(object sender, TransactionEventArgs e)
        {
             //e.Transaction.TransactionInformation contains the Id
        }

Upvotes: 0

Related Questions