服务器故障转移后 TransactionScope 是否仍在运行?服务器故障转移时数据库如何自动回滚更改?

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

这是我的代码

 using (var context = DbContextCreator.Create())
    {
        var transactionOptions = new TransactionOptions { Timeout = TransactionManager.DefaultTimeout }; // 60 seconds. 

        using (var dbContextTransaction = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
        {
            try
            {
                context.Database.ExecuteSqlCommand("SELECT TOP 1 Id FROM SRE.ActionHistory WITH (TABLOCKX, HOLDLOCK)");

                bool isDuplicated = context.ActionHistory
                    .Any(x => x.StatusId == (int)eActionHistoryStatus.Pending &&
                                x.ActionId == (int)Action &&
                                x.DateTime >= timeToCheck &&
                                x.CustomerId == Customer.Id);
                if (!isDuplicated)
                {
                    context.ActionHistory.Add(actionHistory);
                    context.SaveChanges();
                    dbContextTransaction.Complete();
                    return actionHistory;
                }
                throw new BizException(BizErrorCodes.NotAllowedToDoAction);
            }
            catch (Exception ex)
            {
                // It will roll back automatically if the Complete() method isn't invoked or the timeout takes longer than the specified timeout.
                throw;
            }

        }

    }
}

我有两台服务器,一台用于 .NET 代码,另一台用于数据库。

我期望故障转移的服务器是保存.NET代码的服务器。

实际上,即使服务器出现故障,我也需要释放锁。

为了让我的代码干净,我应该使用 Transaction Scope 或 BeginTransaction 哪一个?

c# sql-server entity-framework transactions transactionscope
1个回答
0
投票

当 SQL 客户端连接因故障转移而终止时,SQL Server 将回滚事务。

© www.soinside.com 2019 - 2024. All rights reserved.