【问题标题】:How many times to call .SaveChangesAsync() in .BeginTransaction() EF Core 3.1在 .BeginTransaction() EF Core 3.1 中调用 .SaveChangesAsync() 多少次
【发布时间】:2020-06-25 07:26:39
【问题描述】:

.Remove.Update.Add 等每次更改,请致电SaveChangesAsync

using (var transaction = _unitOfWork.BeginTransaction())
            {
                try
                {
                    var structureProfile = await _unitOfWork.StructureProfiles.GetByStructureIdAsync(id);

                    if (structureProfile != null)
                    {
                        _unitOfWork.StructureProfiles.Remove(structureProfile);
                        await _unitOfWork.SaveChangesAsync();
                    }

                    _unitOfWork.Structures.Remove(structure);
                    await _unitOfWork.SaveChangesAsync();

                    await transaction.CommitAsync();
                    return NoContent();
                }
                catch (Exception)
                {
                    await transaction.RollbackAsync();
                    throw;
                }
            }

或者最后打电话给SaveChangesAsync()

using (var transaction = _unitOfWork.BeginTransaction())
        {
            try
            {
                var structureProfile = await _unitOfWork.StructureProfiles.GetByStructureIdAsync(id);

                if (structureProfile != null)
                {
                    _unitOfWork.StructureProfiles.Remove(structureProfile);
                    //await _unitOfWork.SaveChangesAsync(); -- Remove this part?
                }

                _unitOfWork.Structures.Remove(structure);
                await _unitOfWork.SaveChangesAsync();

                await transaction.CommitAsync();
                return NoContent();
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                throw;
            }
        }

【问题讨论】:

  • 我们不知道您的代码要做什么,也不知道您的 _unitOfWork 是什么类型。请尝试在您的问题中包含相关详细信息,而不仅仅是发布代码墙。
  • DbContext 一个工作单元。您不需要显式事务或多次调用SaveChangesAsyncSaveChangesAsync 将保留工作单元记录的所有更改,即 DbContext 在内部使用显式事务
  • 看起来您尝试实现 Repository anti 模式。这是在像 NHibernate 和 EF 这样的 ORM 变得司空见惯之前使用的 较低级别 抽象。查看 Gunar Peipman 的 No need for Repositories and Unit of Work with EF Core 以获得详细说明,这也解释了为什么您的 Remove 可能会执行 10 次插入和 30 次更新
  • 至于您的控制器操作,编写它们的正确方法是注入请求范围或瞬态 DbContext(从不单例或长寿命的 DbContext),修改根据需要没有显式事务*的实体,并且在返回之前只调用一次SaveChangesAsync。 EF 将负责批处理所有更改并在事务中执行它们

标签: c# asp.net-core-3.1 ef-core-3.1


【解决方案1】:

在您的情况下,使用单个方法执行整个工作单元,您不需要事务:​​SaveChangesAsync 将作为单个事务执行实际查询。

事务变得有用,例如,当工作分散在多个方法中时,每个方法都对自己的部分负责,包括他们自己的SaveChangesAsync。然后,要么您最终显式提交事务,要么处置其对象,使其回滚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 2021-08-09
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2012-07-14
    相关资源
    最近更新 更多