gpt4 book ai didi

c# - 在 Entity Framework Core 的不同方法中使用相同的事务

转载 作者:太空狗 更新时间:2023-10-29 22:18:31 25 4
gpt4 key购买 nike

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

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


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

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

例如,我有一个 Entity Framework 数据库上下文:

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 as error exception for warning 'RelationalEventId.AmbientTransactionWarning': An ambient transaction has been detected. Entity Framework Core does not support ambient transactions.

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://learn.microsoft.com/en-us/ef/core/saving/transactions ),但我没有 Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade 上的方法 UseTransaction。 p>

最佳答案

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

这是一个示例代码,您可以在启动时使用它。虽然还没有在真实场景中测试过:

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>();

关于c# - 在 Entity Framework Core 的不同方法中使用相同的事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com