我怎样才能执行与此等效的操作?我的理解是,这对于 TransactionScopes 来说是不可能的 https://stackoverflow.com/questions/2741988/nested-child-transactionscope-rollback但我想以其他方式完成同等的任务:
业务逻辑类:
public bool Bar()
{
try
{
using (var tsWork = new TransactionScope())
{
ComplicatedDataImportCode(somedata);
FlagRecordInDatabaseAsImported(); // this is the same record that's modified in the catch
tsWork.Complete();
return true;
}
catch (DuplicateDataException err)
{
// if we got here, the above transaction should have rolled back,
// so take that same record in the database and update it to "Duplicate".
FlagSameRecordInDatabaseAsDuplicate(err.Message);
}
return false;
}
现在这工作正常,直到我将所有这些封装在事务中(可能是我想在执行断言后回滚的集成测试)。
简单的测试来证明我的观点:
public void CanTest()
{
// Arrange
var foo = new Foo();
using (var ts = new TransactionScope())
{
// Act
var success = foo.Bar();
// Assert
if (success)
{
Assert.That(SomethingThatTestsThatTheDataWasImported);
}
else
{
Assert.That(SomethingThatTestsThatTheRecordWasMarkedAsDuplicate);
}
// Now that we have been able to perform our Asserts, rollback.
}
}
最终,代码中Foo.Bar()
可以修改以适应解决方案,但是,代码ComplicatedDataImportCode()
无法针对此解决方案进行修改,因此这是我真正需要确保在故障场景中正确回滚的。
再次,根据我在本问题开头引用的帖子,我明白 TransactionScopes 不能用于执行此操作。我在这里使用 TransactionScopes 来指示我想要做什么,并且正在寻找实现此功能的最佳替代方法。
是不是您正在使用的 DBMS 必须支持这一点?
例如,SQL Server 并不真正支持嵌套事务,但是,您可以使用 SQL Server保存点 http://msdn.microsoft.com/en-us/library/ms378414%28v=sql.90%29.aspx.
一篇文章 http://fgheysels.blogspot.com/2006/11/nested-transactions-in-sql-server.html几年前我在博客上写过。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)