c# - 事务范围不适用于 .net 中的多个操作
问题描述
我在 DoWork() 方法中有多个操作,我正在使用事务范围,但它没有按预期工作。
每当 DataInsert2() 中出现故障时,它应该恢复 DataInsert1() 和 DataInsert2()。但目前它只恢复 DataInsert2()..?
让我知道我是否在这里犯了任何错误。
//做工作()
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();
}
}
//数据插入1
public bool DataInsert1()
{
bool fileUploadStatus=false;
try
{
DAL.InsertDetails1()
fileUploadStatus=true;
}
catch (Exception ex)
{
log.Info(string.Format(UploadMessages.FailedMsg));
}
return fileUploadStatus;
}
//数据插入2
public bool DataInsert2()
{
try
{
DAL.InsertDetails2()
}
catch (Exception ex)
{
log.Info(string.Format(UploadMessages.FailedMsg));
}
}
解决方案
您应该能够按如下方式简化代码。您的DataInsert
方法正在吞噬方法抛出的任何异常DAL.InsertDetails
。
public void DoWork()
{
TransactionOptions tranOptions = UtilityBL.GetTransOptions();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, tranOptions))
{
try {
DAL.InsertDetails1();
DAL.InsertDetails2();
scope.Complete();
}
catch (Exception ex)
{
log.Info(string.Format(UploadMessages.FailedMsg));
if (ContextUtil.IsInTransaction)
ContextUtil.SetAbort();
}
}
}
推荐阅读
- php - PHP - foreach 增量超过 1
- java - 为所有用户 Firebase 更新 UI
- scala - 在 Scala 中使用 Twitter Futures 进行异步日志记录
- sql-server - 来自 SQL Server 存储过程的 HTML 报告
- c# - 如何在 xamarin 中启动更新的活动
- mysql - mysql UPDATE 语句 where pricelist.import_date = ( SELECT max(pricelist.import_date) )
- java - Java10中的HttpRequest.BodyProcessor在哪里
- android - 在 React Native 中不能使用新导入的组件?
- r - rasterVis::levelplot 标题高度
- python - 使用 applescript 将消息发送到新的联系人/线程