这是我的代码
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 哪一个?
当 SQL 客户端连接因故障转移而终止时,SQL Server 将回滚事务。