如何在Entity Framework Core中实现环境事务?

我需要在两个模型下实现事务(使用两个分离的有界上下文)。 所以这样的代码:

using (TransactionScope scope = new TransactionScope()) { //Operation 1 using(var context1 = new Context1()) { context1.Add(someCollection1); context1.SaveChanges(); } //Operation 2 using(var context2 = new Context2()) { context2.Add(someCollection2); context2.SaveChanges(); } scope.Complete(); } 

返回exception:

已检测到环境事务。 entity framework核心不支持环境事务。 请参阅http://go.microsoft.com/fwlink/?LinkId=800142

在Link中,他们建议在两个上下文中使用一个连接。 并使用context2来使用context1的块。

但如果我为每个型号使用自己的控制器/服务:

 using (TransactionScope scope = new TransactionScope()) { service1.DoWork(); service2.DoWork(); scope.Complete(); } 

我该如何实现呢? 在方法中添加连接作为参数 – 似乎很荒谬。 与连接的Init服务也是个坏主意。

您可以像这样使用’contexts’:

 using (var context1 = new Context1()) { using (var transaction = context1.Database.BeginTransaction()) { try { context1.Add(someCollection1); context1.SaveChanges(); // if we don't have errors - next step using(var context2 = new Context2()) { // second step context2.Add(someCollection2); context2.SaveChanges(); } // if all success - commit first step (second step was success completed) transaction.Commit(); } catch (Exception) { // if we have error - rollback first step (second step not be able accepted) transaction.Rollback(); } } } 

如果您将使用许多控制器/服务,那么您可以使用内部方法将DbConnection传递到您的服务方法中。 您必须封装低层逻辑。

与连接的Init服务也是个坏主意。 – 可能你是对的。 但您可以尝试使用一个连接和单个事务初始化两个方法。

看下一个答案,他们可以帮助您:

  • 由于方法调用而嵌套的DbContext – entity framework
  • 一个具有多个dbcontexts的事务
  • entity framework核心 – 使用事务