如何在 Linq To Entites 中维护事务
假设我同时在以下表中插入记录
表1
表2
表3
表4
表5
现在我想做的是,如果表3插入过程中出现任何异常或错误,那么之前插入的记录(例如表1和表2)必须回滚。 ..
我怎样才能管理这样的交易?
Suppose I am inserting records in following Tables at the same time
Table 1
Table 2
Table 3
Table 4
Table 5
Now What I want to do is, In-case of any exception or error occurs during insertion in Table 3 , then record which are inserted before that (eg. in Table 1 and Table 2) must be roll back...
How can I manage transaction like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Entity Framework 4 的默认行为
。事务是隐式的。一旦您调用 savechanges,任何错误都会触发回滚。
This is the default behaviour of Entity Framework 4
The transaction is implicit .. as soon as you call savechanges any errors will trigger a rollback.
默认情况下,SaveChanges 将在事务中执行(请参阅中的备注部分文档)
如果您想要对事务进行更多控制,您可以将 savechanges 块包装在 TransactionScope 中。然后 SaveChanges 将获取您的环境事务并使用该事务。
当您需要分布式事务时(例如具有多个上下文或使用 WCF),这可能很有用。
正如您提到的,您使用不同的模型,您将在一个 TransactionScope 中使用两个 ObjectContext(并使用 一些逻辑 与 AcceptAllChanges)
您的代码将如下所示:
By default, SaveChanges will execute in a transaction (see the Remarks part in the docs)
If you want more control over the transaction, you can wrap your savechanges block in a TransactionScope. SaveChanges will then pickup your ambient transaction and use that one.
This can be useful when you want a distributed transaction (for example with multiple contexts or if you use WCF).
As you mentioned that you use different models, you would use both ObjectContexts within one TransactionScope (and use some logic with AcceptAllChanges)
Your code would then look like: