小编Hri*_*hev的帖子

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

我正在将 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 …
Run Code Online (Sandbox Code Playgroud)

c# transactions entity-framework-core .net-core

7
推荐指数
1
解决办法
2132
查看次数