问题描述
我怎样才能做到这一点?我的理解是使用 TransactionScopes 是不可能的 但我想在一些其他方式:
How can I perform the equivalent of this? My understanding is that this is impossible with TransactionScopes but I'd like to accomplish the equivalent in some other way:
业务逻辑类:
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;
}
现在一切正常,直到我将所有这些都封装在一个事务中(可能是我想在执行断言后回滚的集成测试).
Now this works fine, until I encapsulate all of this inside of a transaction (perhaps an integration test that I want to rollback after performing asserts).
简单的测试来证明我的观点:
Simple test to prove my point:
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()
中的代码不能针对该解决方案进行修改,并且因此,我真正需要的是确保在失败情况下正确回滚.
Ultimately, the code in Foo.Bar()
can be modified to accommodate a solution however, the code in ComplicatedDataImportCode()
cannot be modified for this solution, and is consequently what I really need to make sure I properly rollback in the failure scenario.
再次,根据我在此问题开头引用的帖子,我了解 TransactionScopes 不能用于执行此操作.我在这里使用 TransactionScopes 来表明我想要做什么,并且正在寻找实现此功能的最佳替代方法.
Again, I understand that TransactionScopes cannot be used to do this, according to the post that I referenced at the beginning of this question. I used TransactionScopes here to indicate what I wanted to do, and am looking for the best alternative way to implement this functionality.
推荐答案
不是说你使用的DBMS必须支持这个吗?
Isn't it so that this must be supported by the DBMS you're using ?
例如,SQL Server 并不真正支持嵌套事务,但是,对于 SQL Server,您可以使用 保存点.
SQL Server doesn't really support nested transactions for instance, however, with SQL Server you can use savepoints.
一篇文章我写的几年前在我的博客上.
An article I've written some years ago on my blog.
这篇关于.NET 中的嵌套事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!