簡體   English   中英

在.BeginTransaction() EF Core 3.1 中調用.SaveChangesAsync() 多少次

[英]How many times to call .SaveChangesAsync() in .BeginTransaction() EF Core 3.1

調用SaveChangesAsync每個更改,例如.Remove.Update.Add

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

在您的情況下,使用單個方法執行整個工作單元,您不需要事務: SaveChangesAsync將作為單個事務執行實際查詢。

事務變得有用,例如,當工作分布在多個方法中時,每個方法都對自己的部分負責,包括他們自己的SaveChangesAsync 然后,要么您最終顯式提交事務,要么處置其 object,導致它回滾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM