提交事务时获取事务ID

问题描述 投票:1回答:1

我正在使用事务范围的IEnlistmentNotification接口,我希望在范围完成后访问提交方法中的当前事务ID,如下所示:

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

但是我收到错误,因为现在transaction.current为null。从我检查的登记实例具有transactionId的私有成员,但我无法访问它的保护级别。

在范围完成时是否有另一种获取事务ID的方法?

c# transactions transactionscope
1个回答
0
投票
        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
        }
© www.soinside.com 2019 - 2024. All rights reserved.