如何在 Linq To Entites 中维护事务

发布于 2024-12-23 01:46:56 字数 141 浏览 2 评论 0原文

假设我同时在以下表中插入记录
表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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

〆一缕阳光ご 2024-12-30 01:46:56

这是 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.

错爱 2024-12-30 01:46:56

默认情况下,SaveChanges 将在事务中执行(请参阅中的备注部分文档)

如果您想要对事务进行更多控制,您可以将 savechanges 块包装在 TransactionScope 中。然后 SaveChanges 将获取您的环境事务并使用该事务。

当您需要分布式事务时(例如具有多个上下文或使用 WCF),这可能很有用。

正如您提到的,您使用不同的模型,您将在一个 TransactionScope 中使用两个 ObjectContext(并使用 一些逻辑 与 AcceptAllChanges)

您的代码将如下所示:

using (TransactionScope scope = new TransactionScope()) 
{ 
    //Do something with context1 
    //Do something with context2


    //Save Changes but don't discard yet 
    context1.SaveChanges(false); 

    //Save Changes but don't discard yet 
    context2.SaveChanges(false);


    //if we get here things are looking good. 
    scope.Complete(); 

    //If we get here it is save to accept all changes. 
    context1.AcceptAllChanges(); 
    context2.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:

using (TransactionScope scope = new TransactionScope()) 
{ 
    //Do something with context1 
    //Do something with context2


    //Save Changes but don't discard yet 
    context1.SaveChanges(false); 

    //Save Changes but don't discard yet 
    context2.SaveChanges(false);


    //if we get here things are looking good. 
    scope.Complete(); 

    //If we get here it is save to accept all changes. 
    context1.AcceptAllChanges(); 
    context2.AcceptAllChanges();
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文