【问题标题】:Entity Framework Core using Multiple Contexts with different connection strings in the same TransactionEntity Framework Core 在同一个事务中使用具有不同连接字符串的多个上下文
【发布时间】:2019-11-16 17:13:32
【问题描述】:

使用 EF Core,建议使用以下事务:

using (var dbContextTransaction = _context.Database.BeginTransaction())
{

}

如何使用可以跨越多个上下文的事务,这些上下文也有不同的连接字符串,即我们不能使用 SqlConnection.BeginTransation,因为这两个上下文有不同的连接字符串。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    当您需要一个范围比您正在使用的上下文更大的事务时,您可以使用TransactionScope 对象。这需要 Entity Framework Core 2.1,如 https://docs.microsoft.com/en-us/ef/core/saving/transactions 所述:

    使用 System.Transactions

    注意:此功能是 EF Core 2.1 中的新功能。

    如果您需要在更大范围内进行协调,可以使用环境事务。

    所以使用这样的东西:

    using (var scope = new TransactionScope()) {
        // create and work with context here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多