实体框架核心事务中的多个 SaveChanges 有何意义?

Hri*_*hev 7 c# transactions entity-framework-core .net-core

我正在将 EF 用于我的 .net-core 应用程序,我想知道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();
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

如您所见,事务中需要执行 3 个数据库操作。储蓄存款,更新债务,更新家庭余额。现在,我可以选择SaveChanges在每次操作之后放置,就像上面的代码所示,或者我可以完全丢弃前 2 次调用SaveChanges并且方法的行为不会以任何方式改变。我在网上找到的大多数示例都包含对 SaveChanges 的多次调用,我想这两种方法之间一定有一些区别。然而,我找不到任何信息,这种差异究竟是什么。有人可以对这个问题有所了解吗?

Tom*_*ada 6

有时调用 SaveChanges 是很实用的,因为您可以检索插入记录的脏写入 ID。在您提到的情况下,它可能用于将数据库操作拆分为更小的部分,因此当第一个小操作失败时,您将保存其余代码的执行,这意味着需要回滚的操作更少。