即使未调用 System.Transactions.TransactionScope.Commit() 也已提交数据
在什么情况下,即使抛出了异常并且最外层作用域从未调用过提交,包装在 System.Transactions.TransactionScope 中的代码仍然可以提交?
using (var tx = new TransactionScope())
包装了一个顶级方法,它以相同的方式调用也使用 TransactionScope
的方法。
我正在使用带有关联表适配器的类型化数据集。适配器中的命令是否由于某种原因未征用?你们中有人知道如何检查他们是否加入了环境 TransactionScope 中吗?
Under what circumstances can code wrapped in a System.Transactions.TransactionScope
still commit, even though an exception was thrown and the outermost scope never had commit called?
There is a top-level method wrapped in using (var tx = new TransactionScope())
, and that calls methods that also use TransactionScope
in the same way.
I'm using typed datasets with associated tableadapters. Could it be that the commands in the adapter aren't enlisting for some reason? Do any of you know how one might check whether they are enlisting in the ambient TransactionScope or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案是因为我在
SqlConnection
对象之后创建了TransactionScope
对象。我从这个:
转到这个:
现在它可以工作了!
因此,这个故事的寓意是首先创建您的
TransactionScope
。The answer turned out to be because I was creating the
TransactionScope
object after theSqlConnection
object.I moved from this:
to this:
and now it works!
So the moral of the story is to create your
TransactionScope
first.明显的情况是显式指定新的 (
RequiresNew
) / null (Suppress
) 事务 - 但也存在超时/解除绑定故障,可能导致连接丢失交易。请参阅此之前的帖子(修复只是连接字符串更改),或完整详细信息。The obvious scenario would be where a new (
RequiresNew
) / null (Suppress
) transaction is explicitly specified - but there is also a timeout/unbinding glitch that can cause connections to miss the transaction. See this earlier post (the fix is just a connection-string change), or full details.了解
TransactionScope
的工作原理:它在使用范围开始时设置属性
System.Transactions.Transaction.Current
,然后在使用范围结束时将其设置回以前的值。先前的值取决于声明给定范围的位置。它可以在另一个范围内。
您可以这样修改代码:
我向那些代码更复杂并且不能简单地更改代码以首先打开数据库连接的人展示了这种可能性。
Be aware how
TransactionScope
works:It sets property
System.Transactions.Transaction.Current
at the begining of using scope and then set it back to previous value at end of using scope.Previous value depends on where given scope is declared. It can be inside another scope.
You can modify code like this:
I show this possibility for those who have their code more complicated and cannot simply change code to open DB connection first.
此示例(C#、.NetFramework 4.7.1)展示了即使代码包装在
TransactionScope
中,我们也可以如何持久保存到数据库。第一个insert
将回滚,第二个insert
将在没有事务的情况下插入。请参阅我的相关帖子,我在其中寻求有关如何检测的帮助这。
This example (C#, .NetFramework 4.7.1) shows how we can persist to the database even if the code is wrapped in a
TransactionScope
. The firstinsert
will be rolled back, and the secondinsert
will be inserted without transaction.See my related post, where I ask for help in how to detect this.