如何在 C# 中将 TranscactionScope 限制为给定的 DataBaseContext?
我希望 100% 当我使用这种模式时,
using (var scope = new TransactionScope())
{
db1.Foo.InsertOnSubmit(new Foo()); // just an example
db1.SubmitChanges();
scope.Commit();
}
事务范围将仅引用 db1 而不是 db2(db1 和 db2 是 DataBaseContext 对象)。那么如何将范围限制为仅 db1 呢?
先感谢您。
I would like to be 100% that when I use such pattern
using (var scope = new TransactionScope())
{
db1.Foo.InsertOnSubmit(new Foo()); // just an example
db1.SubmitChanges();
scope.Commit();
}
the transaction scope will only refer to db1 not db2 (db1 and db2 are DataBaseContext objects). So how to limit scope to db1 only?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
TransactionScope
的优势在于它会自动捕获其中的所有内容,直至调用堆栈(除非另一个TransactionScope
具有RequiresNew
或Supress< /代码>)。如果这不是您想要的,您应该使用另一种机制来处理事务。
一种方法是打开
SqlConnection
并调用BeginTransaction
来获取事务,然后在创建数据上下文时使用该数据库连接。 (也许您必须在数据上下文上设置事务属性,我不确定)。在上面给出的示例中,使用
TransactionScope
是完全多余的。只有一个函数调用实际修改数据库:SubmitChanges
,并且如果尚不存在事务,它总是创建自己的事务。原因是,当您执行多个操作时,SubmitChanges
要么全部成功,要么全部失败。如果您只追求单个数据上下文的单个SubmitChanges
调用的事务完整性,那么您可以直接删除TransactionScope
。The strength of
TransactionScope
is that it automatically catches everything within it, down the call stack (unless anotherTransactionScope
withRequiresNew
orSupress
). If this is not what you want, you should use another mechanism for the transaction handling.One way is to open
SqlConnection
and callBeginTransaction
to get a transaction, then use that DB connection when creating your data context. (Maybe you'll have to set the Transaction propery on the data context, I'm not sure).In the example you have given above, the use of a
TransactionScope
is totally redundant. There is only one function call that actually modifies the database:SubmitChanges
and it always creates its own transaction if there isn't already one existing. The reason is that when you're doing several operationsSubmitChanges
should either succeed in them all or fail all. If you're only after transactional integrity for a singleSubmitChanges
call for a single data context, then you can just drop theTransactionScope
.据我所知,您所追求的正是您所写的,编译器将确保您提交时事务完成。
As far as I know, what you are after is exactly what you have written, the compiler will ensure that transaction is completed when you commit.
如果您使用:
您可以确保为此范围创建一个新的事务,因此您在范围内所做的每件事都有自己的事务,并且永远不会使用任何现有的环境事务。
If you use:
You can be sure a new transcation is created for this scope, so everyting you do inside the scope has its own transaction, and will never use any existing ambient transactions.