跨 Azure SQL 和本地 sql 服务器的分布式事务导致错误

Distributed transactions accross Azure SQL and on premises sql server causes errors

是否可以在本地 SQL 服务器实例和 Azure SQL 数据库之间进行交易。

我有以下测试用例。

public class TransactionsTest
{
    [Fact]
    public void Test1()
    {
        var premisesDatabaseContext = new OnPremisesDatabaseContext();
        var azureSQLDatabaseContext = new AzureSQLDatabaseContext();

        using (TransactionScope scope = new TransactionScope())
        {
            premisesDatabaseContext.Database.Connection.Open();
            azureSQLDatabaseContext.Database.Connection.Open();

            scope.Complete();
        }
    }

    [Fact]
    public void Test2()
    {
        var premisesDatabaseContext = new OnPremisesDatabaseContext();
        var azureSQLDatabaseContext = new AzureSQLDatabaseContext();

        using (TransactionScope scope = new TransactionScope())
        {
            azureSQLDatabaseContext.Database.Connection.Open();
            premisesDatabaseContext.Database.Connection.Open();

            scope.Complete();
        }
    }
}

看起来很简单。但是当我打开第二个连接时,两个测试用例都失败并出现不同的错误。

这是错误的详细信息。

// TEST 1
System.Reflection.TargetInvocationException: 
Exception has been thrown by the target of an invocation. 
--->
System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Transactions.Transaction.GetPromotedToken()

// TEST 2
System.Transactions.TransactionPromotionException:
There is a promotable enlistment for the transaction which has a PromoterType value that is not recognized by System.Transactions. 
1c742caf-6680-40ea-9c26-6b6846079764

我想知道是否可以做到这一点。如果不可能,有什么替代方案?

你不能

Azure sql 数据库使用 Elastic Transactions。本地服务器使用 Microsoft Distributed Transaction Coordinator (MSDTC).

Azure 不支持 MSDTC,根据弹性事务文档,

Only transactions across databases in SQL DB are supported. Other X/Open XA resource providers and databases outside of SQL DB cannot participate in elastic database transactions. That means that elastic database transactions cannot stretch across on premises SQL Server and Azure SQL Database. For distributed transactions on premises, continue to use MSDTC.

  • 本地 SQL 服务器使用 MSDTC,它在 Azure 上不可用 SQL数据库。

  • Azure SQL 数据库使用弹性事务,不适用于 本地 SQL 服务器。

最简单的解决方案是将所有数据库移动到 Azure 或本地。