【发布时间】:2019-01-29 12:26:26
【问题描述】:
我在 DoWork() 方法中有多个操作,我正在使用事务范围,但它没有按预期工作。
当 DataInsert2() 出现故障时,它应该恢复 DataInsert1() 和 DataInsert2()。但目前它只恢复 DataInsert2()..?
如果我在这里犯了任何错误,请告诉我。
//DoWork()
public void DoWork()
{
try
{
TransactionOptions tranOptions = UtilityBL.GetTransOptions();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, tranOptions))
{
if (DataInsert1())
{
DataInsert2() ;
}
scope.Complete();
}
}
catch (Exception ex)
{
log.Info(string.Format(UploadMessages.FailedMsg));
if (ContextUtil.IsInTransaction)
ContextUtil.SetAbort();
}
}
//DataInsert1
public bool DataInsert1()
{
bool fileUploadStatus=false;
try
{
DAL.InsertDetails1()
fileUploadStatus=true;
}
catch (Exception ex)
{
log.Info(string.Format(UploadMessages.FailedMsg));
}
return fileUploadStatus;
}
//DataInsert2
public bool DataInsert2()
{
try
{
DAL.InsertDetails2()
}
catch (Exception ex)
{
log.Info(string.Format(UploadMessages.FailedMsg));
}
}
【问题讨论】:
-
在不知道
DAL中的内容的情况下,无法判断为什么这可能不起作用。特别是,TransactionScope本身并没有真正做任何事情,在其中运行的代码必须是事务感知的并选择加入。如果(例如)它跨越新线程来工作,或者如果你的工作“ re doing 实际上并不支持事务。 -
看起来您依赖于在
DoWork()中捕获的异常来回滚您的事务,但在数据插入方法中您正在吞噬它们。 -
@ChrisPickford 我也尝试在数据插入捕获块中添加事务 abort()。但仍然是同样的问题。
-
stackoverflow.com/questions/494550/… 您不需要显式回滚,因此您甚至可以将您的 try-catch 块放在事务范围之外。它开箱即用,您只需要 Complete()。
标签: c# sql asp.net .net transactions