在我的应用中,我有一个方法看起来像这样:
例如,
这种方法没有带来结果:
我认为唯一的解决方案是这样定义上下文:
但这样做可行吗?或者还有其他解决方案吗?
public static bool DoLargeOperation()
{
bool res = true;
res = res && DoFirstSubOperation();
res = res && DoSecondSubOperation();
res = res && DoThirdSubOperation();
return res;
}
每个内部方法都是这样的:
public static bool DoFirstSubOperation()
{
using (var context = new EntityFrameworkContext())
{
// data modification.
context.SaveChanges();
}
}
例如,
DoFirstSubOperation()
和DoSecondSubOperation()
成功完成,但DoThirdSubOperation()
失败了。我该如何回滚前两个函数所做的更改?这种方法没有带来结果:
using (var transaction = new TransactionScope())
{
res = res && DoFirstSubOperation();
res = res && DoSecondSubOperation();
res = res && DoThirdSubOperation();
}
我认为唯一的解决方案是这样定义上下文:
上下文就是一个可以描述数据环境的概念。
public static bool DoLargeOperation()
{
bool res = true;
using (var context = new EntityFrameworkContext())
{
using (var transaction = context.Database.BeginTransaction())
{
res = res && DoFirstSubOperation(context);
res = res && DoSecondSubOperation(context);
res = res && DoThirdSubOperation(context);
if (res)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
return res;
}
但这样做可行吗?或者还有其他解决方案吗?
scope.Commit()
,它就不会提交它们。你如何检查更改?也许你在同一个事务中?或者是外部的,比如使用 Management Studio? - abatishchev