如何在Linq To Entites中进行maintan交易

Mox*_*hah 5 c# linq linq-to-entities transactions

假设我同时在下表中插入记录
表1
表2
表3
表4
表5

现在我想要做的是,如果在表3中插入期间发生任何异常或错误,那么在此之前插入的记录(例如表1和表2中)必须回滚...

我该如何管理这样的交易?

Wou*_*ort 3

默认情况下,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();
 }
Run Code Online (Sandbox Code Playgroud)