C# 在.BeginTransaction()EF Core 3.1中调用.SaveChangesSync()的次数

C# 在.BeginTransaction()EF Core 3.1中调用.SaveChangesSync()的次数,c#,asp.net-core-3.1,ef-core-3.1,C#,Asp.net Core 3.1,Ef Core 3.1,调用savechangesync每次更改,如。删除、。更新或。添加 using (var transaction = _unitOfWork.BeginTransaction()) { try { var structureProfile = await _unitOfWork.StructureProfiles.GetByStructureIdAsync(id);

调用
savechangesync
每次更改,如
。删除
。更新
。添加

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;
                }
            }
或者在最后一部分调用
savechangessync()

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;
            }
        }

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


事务变得很有用,例如,当工作分布在多个方法中,每个方法负责自己的部分,包括自己的
savechangessync
。然后,要么最终显式提交事务,要么处置其对象,导致其回滚。

我们不知道您的代码试图做什么,也不知道您的
\u unitOfWork
是什么类型。请尝试在您的问题中包含相关细节,而不仅仅是张贴代码墙。DbContext是一个工作单元。您不需要显式事务或多次调用
savechangesync
savechangesync
将保留工作单元记录的所有更改,即使用显式事务的DbContext内部看起来像您试图实现存储库反模式。这是在NHibernate和EF等ORM普及之前使用的较低级别的抽象。查看Gunar Peipman的详细解释,这也解释了为什么您的
Remove
可能会在侧面执行10次插入和30次更新。对于控制器操作,正确的写入方式是注入请求范围或瞬态DbContext(而不是单例或长期的DbContext),根据需要修改实体,无需显式事务*并在返回之前只调用一次
savechangesync
。EF将负责批处理所有更改,并在事务内执行这些更改