【问题标题】:Use the same transaction in different methods with Entity Framework Core使用 Entity Framework Core 在不同的方法中使用相同的事务
【发布时间】:2016-11-15 14:06:26
【问题描述】:

编辑 (02/03/2018): 由于 Entity Framework Core 2.1,EF Core 实现了事务、跨上下文事务、环境事务和事务范围,所以这个问题现在已经过时了。

这是有关 EF Core 中事务的官方文档:https://docs.microsoft.com/en-us/ef/core/saving/transactions


如何在不同的方法中使用相同的事务?目标是在发生错误时提交或回滚所有修改。

我正在使用 Entity Framework Core 1.1.0-preview1-finalSQL Server 2014。

例如,我有一个实体框架数据库上下文:

public class ApplicationDatabaseContext : DbContext
    {
        public ApplicationDatabaseContext(DbContextOptions<ApplicationDatabaseContext> options)
           : base(options)
        { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TransactionLog1>(entity =>
            {
                entity.ToTable("TRANSACTION_LOG_1");

                entity.Property(e => e.CreationDate)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("getdate()");
            });

            modelBuilder.Entity<TransactionLog2>(entity =>
            {
                entity.ToTable("TRANSACTION_LOG_2");

                entity.Property(e => e.CreationDate)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("getdate()");
            });
        }

        public virtual DbSet<TransactionLog1> TransactionLog1 { get; set; }
        public virtual DbSet<TransactionLog2> TransactionLog2 { get; set; }
    }

我有两个类来处理数据,它们都使用相同的上下文:

public interface IRepository1
{
    void Create(Guid key);
}

public sealed class Repository1 : IRepository1
{
    private readonly ApplicationDatabaseContext _dbContext;

    public Repository1(ApplicationDatabaseContext dbcontext)
    {
        _dbContext = dbcontext;
    }

    public void Create(Guid key)
    {
        using (_dbContext.Database.BeginTransaction())
        {
            try
            {
                _dbContext.TransactionLog1.Add(new TransactionLog1 { Key = key });
                _dbContext.SaveChanges();

                _dbContext.Database.CommitTransaction();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

public interface IRepository2
{
    void Create(Guid key);
}

public sealed class Repository2 : IRepository2
{
    private readonly ApplicationDatabaseContext _dbContext;

    public Repository2(ApplicationDatabaseContext dbcontext)
    {
        _dbContext = dbcontext;
    }

    public void Create(Guid key)
    {
        using (_dbContext.Database.BeginTransaction())
        {
            try
            {
                _dbContext.TransactionLog2.Add(new TransactionLog2 { Key = key });
                _dbContext.SaveChanges();

                _dbContext.Database.CommitTransaction();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

在我的业务逻辑中,我有一个服务,我想在我的第一个存储库上调用方法 void Create(Guid key),然后从我的第二个存储库中调用相同的方法并仅在以下情况下提交两者都没有错误发生(如果在第二个方法中发生任何错误,我想回滚在第一个方法中完成的提交)。

我该怎么做? Entity Framework Core 和事务的最佳实践是什么?

我尝试了几件事,像这样,但它从来没有用过(使用这种方法我有错误):

Warning 作为警告的错误异常 'RelationalEventId.AmbientTransactionWarning':环境事务 已被检测到。 Entity Framework Core 不支持环境 交易。

public sealed class Service3 : IService3
{
        private readonly IRepository1 _repo1;
        private readonly IRepository2 _repo2;

        public Service3(IRepository1 repo1, IRepository2 repo2)
        {
            _repo1 = repo1;
            _repo2 = repo2;
        }

        public void Create(Guid key)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    _repo1.Create(key);
                    _repo2.Create(key);

                    scope.Complete();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
}

我阅读了文档,尤其是此页面 (https://docs.microsoft.com/en-us/ef/core/saving/transactions),但我没有 Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade 上的方法 UseTransaction。 p>

【问题讨论】:

标签: c# transactions entity-framework-core asp.net-core-1.0 sql-server-2014-express


【解决方案1】:

一种可能的方法是使用中间件并将开始/提交/回滚的逻辑放在那里。例如,在每个请求开始时,您都会在底层数据库连接上开始一个事务。在请求结束时提交或回滚事务。由于您很可能每个请求都使用单个上下文实例,这将解决您的问题。此外,您将从您的存储库/服务类中提取此问题。

这是一个示例代码,您可以将其用作初创公司。虽然还没有在真实场景中测试过:

public class TransactionPerRequestMiddleware
{
    private readonly RequestDelegate next_;

    public TransactionPerRequestMiddleware(RequestDelegate next)
    {
        next_ = next;
    }

    public async Task Invoke(HttpContext context, ApplicationDbContext dbContext)
    {
        var transaction = dbContext.Database.BeginTransaction(
            System.Data.IsolationLevel.ReadCommitted);

        await next_.Invoke(context);

        if (context.Response.StatusCode == 200)
        {
            transaction.Commit();
        }
        else
        {
            transaction.Rollback();
        }
    }
}

然后在你的Startup.Configure() 方法中:

app.UseMiddleware<TransactionPerRequestMiddleware>();

【讨论】:

  • 哼哼有趣。我终于以不同的方式找到了解决方案,但您的解决方案很有意义,我会测试它是否比我最终做的更好
  • 我刚刚发布了我昨晚找到的解决方案的答案。我会测试你的,我会告诉你它是否比我的更好。还是谢谢
  • 一旦实体框架本身将每个请求包装为事务,您就可以避免这个中间件,并且避免显式事务和显式“saveChanges”,并且您会得到相同的结果......我错了吗?跨度>
  • 这是否对数据库性能没有任何影响,因为您将每个请求都包装在事务中?
  • 如 MSDN 中所述“开始事务需要打开底层存储连接。因此,如果尚未打开连接,则调用 Database.BeginTransaction() 将打开连接。”。您不应该在整个请求时间内都这样做。
【解决方案2】:

编辑 (02/03/2018) : 从 Entity Framework Core 2.1 开始,您可以使用事务、跨上下文事务、环境事务和事务范围,因此您不必实施工作-大约。

这是官方文档:https://docs.microsoft.com/en-us/ef/core/saving/transactions


我终于找到了一个解决方案,等待 Entity Framework Core 的下一个版本,它可以使用事务范围和环境事务。

由于db事务与一个数据库上下文相关,而数据库上下文在我所有的数据访问类中都是相同的(感谢依赖注入),当我在一个进程中启动一个事务时,它会被其他数据访问共享在处理事务之前在同一进程中创建类(我必须将我的 Entity Framework Core 升级到 1.1.0-preview1-final 才能拥有一次性事务)。

具体来说,我有一堂课来处理交易:

public interface ITransactionDealerRepository
{
    void BeginTransaction();

    void CommitTransaction();

    void RollbackTransaction();

    void DisposeTransaction();
}

public sealed class TransactionDealerRepository : BaseEntityFrameworkRepository, ITransactionDealerRepository
{
    public TransactionDealerRepository(MyDBContext dbContext)
       : base(dbContext)
    { }

    public void BeginTransaction()
    {
        _dbContext.Database.BeginTransaction();
    }

    public void CommitTransaction()
    {
        _dbContext.Database.CommitTransaction();
    }

    public void RollbackTransaction()
    {
        _dbContext.Database.RollbackTransaction();
    }

    public void DisposeTransaction()
    {
        _dbContext.Database.CurrentTransaction.Dispose();
    }
}

我在我的服务中使用这个类:

    public void Create(Guid key)
    {
        _transactionProvider.BeginTransaction();

        try
        {
            _repo1.Create(key);
            _repo2.Create(key);

            _transactionProvider.CommitTransaction();
        }
        catch (Exception)
        {
            _transactionProvider.RollbackTransaction();
            throw;
        }
        finally
        {
            _transactionProvider.DisposeTransaction();
        }
    }

【讨论】:

  • 你好@Adrien,你错过了 savechanges() 方法吗?
  • @SheldonLou 您必须调用 your_db_context.SaveChanges() 或 your_db_context.SaveChangesAsync() 但此步骤在数据访问层完成,而不是在业务逻辑层完成。在我的示例中,更改保存在两种方法中:_repo1.Create(key) 和 _repo2.Create(key)
  • 很好,但是您的示例代码存在一些问题。例如,您没有定义/注入 _dbContext。另外,你是通过什么方式在 IServiceCollection 中注册这个 TransactionDealerRepository 的?
  • @AndrienTorris,当你回滚你的事务时,你 DisposeTransaction 上的 CurrentTransaction 不再存在,所以没有必要在代码上留下 finally 语句
  • 顺便说一句,您检查了 RollbackTransaction 吗?它对我不起作用
【解决方案3】:

一旦实体框架本身将每个请求包装为事务,您就可以避免显式事务和显式“saveChanges”,并且您可以原子地提交或回滚所有请求

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2020-04-13
    • 2019-06-27
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多