【发布时间】:2011-08-08 19:46:57
【问题描述】:
我怎样才能做到这一点? My understanding is that this is impossible with TransactionScopes 但我想以其他方式完成等效操作:
业务逻辑类:
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 来表明我想要做什么,并且正在寻找实现此功能的最佳替代方法。
【问题讨论】:
标签: .net .net-4.0 transactions sql-server-2008-r2