postgresql 事务未升级到分布式事务

mjqavswn  于 11个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(128)

我的控制器代码类似于以下内容(匿名)。我预计由于EF Core 6中缺乏分布式事务支持而引发异常,我希望代码尝试将事务升级为分布式事务,因为在同一事务中使用了两个不同的DbConnection和两个不同的DbContext。不同的进程ID,所以它似乎与连接池无关。为什么这段代码似乎可以工作?

using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Npgsql;

namespace Controllers.Test;

[Route("test")]
public sealed class TestController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly IHostEnvironment _host;

    public TestController(
        IConfiguration configuration,
        IHostEnvironment host)
    {
        _configuration = configuration;
        _host = host;
    }

    [HttpGet]
    public void Get()
    {
        using var transactionScope = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromMinutes(30) },
            TransactionScopeAsyncFlowOption.Enabled);

        var fooConnectionString = _configuration.GetConnectionString("foo")!;
        var barConnectionString = _configuration.GetConnectionString("bar")!;

        using var fooConnection = new NpgsqlConnection(fooConnectionString);
        using var barConnection = new NpgsqlConnection(barConnectionString);
        
        fooConnection.Open();
        barConnection.Open();

        using var fooDbContext = new FooDbContext(new DbContextOptionsBuilder<FooDbContext>()
            .UseNpgsql(fooConnection, o => o.UseNodaTime())
            .Options);
        using var barDbContext = new BarDbContext(new DbContextOptionsBuilder<BarDbContext>()
            .UseNpgsql(barConnection, o => o.UseNodaTime())
            .Options);

        var foo = fooDbContext.Foos.OrderBy(x => x.Id).First();
        foo.SequenceNumber++;
        fooDbContext.SaveChanges();

        var bar = barDbContext.Bars.OrderBy(x => x.Id).First();
        bar.SequenceNumber++;
        barDbContext.SaveChanges();

        transactionScope.Complete();
    }
}

字符串
.NET Core 6
Npgsql. martyFrameworkCore.PostgreSQL版本6.0.7
Microsoft. MicrosoftFrameworkCore 6.0.8版

rekjcdws

rekjcdws1#

您运行的是哪个版本的.Net Core?Windows上支持.Net Core 7的分布式事务。如果您针对.Net Core 6构建,您可能会看到预期的异常。Npgsql可能不完全支持它们并忽略或重新使用连接,您可以尝试:

var foo = fooDbContext.Foos.OrderBy(x => x.Id).First();
    foo.SequenceNumber++;
    var bar = barDbContext.Bars.OrderBy(x => x.Id).First();
    bar.SequenceNumber++;

    fooDbContext.SaveChanges();
    barDbContext.SaveChanges();

字符串
来自Npgsql文档:(https://www.npgsql.org/doc/basic-usage.html
虽然Npgsql部分支持这种机制,但由于.NET支持的一些设计问题,它不实现分布式事务的恢复部分。虽然分布式事务可能适合您,但不鼓励使用Npgsql完全依赖它们。

相关问题