我正在为我的 .net-core 应用程序使用 EF,我想知道调用 SaveChanges
之间有什么区别在一个事务中多次调用并且在提交前只调用一次。为了更好地说明我的问题,我将提供一些伪代码。
public async Task<IActionResult> AddDepositToHousehold(int householdId, DepositRequestModel model)
{
using (var transaction = await Context.Database.BeginTransactionAsync(IsolationLevel.Snapshot))
{
try
{
// Add the deposit to the database
var deposit = this.Mapper.Map<Deposit>(model);
await this.Context.Deposits.AddAsync(deposit);
await this.Context.SaveChangesAsync();
// Pay some debts with the deposit
var debtsToPay = await this.Context.Debts
.Where(d => d.HouseholdId == householdId && !d.IsPaid)
.OrderBy(d => d.DateMade)
.ToListAsync();
debtsToPay.ForEach(d => d.IsPaid = true);
await this.Context.SaveChangesAsync();
// Increase the balance of the household
var household = this.Context.Households
.FirstOrDefaultAsync(h => h.Id == householdId);
household.Balance += model.DepositAmount;
await this.Context.SaveChangesAsync();
transaction.Commit();
return this.Ok();
}
catch
{
transaction.Rollback();
return this.BadRequest();
}
}
}
如您所见,事务中需要执行 3 个数据库操作。储蓄存款,更新债务,更新家庭余额。现在,我可以选择放
SaveChanges
每次操作后,就像上面的代码所示,或者我可以完全丢弃对 SaveChanges
的前 2 次调用并且该方法的行为不会以任何方式改变。我在网上找到的大多数示例都包含对 SaveChanges 的多次调用,我想这两种方法之间肯定存在一些差异。然而,我找不到任何信息,这种差异究竟是什么。有人可以对这个问题有所了解吗?
最佳答案
有时调用 SaveChanges 是可行的,因为您可以检索插入记录的脏写 Id。在您提到的情况下,它可能用于将数据库操作拆分为更小的部分,因此当第一个小操作失败时,您将节省其余代码的执行时间,这意味着需要回滚的操作更少。
关于c# - Entity Framework 核心事务中的多个 SaveChanges 有何意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562646/