简体   繁体   中英

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

Call SaveChangesAsync every changes like .Remove , .Update or .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;
                }
            }

Or Call SaveChangesAsync() at last part?

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

In your case, with a single method performing the entire unit of work, you don't need the transaction: SaveChangesAsync will perform the actual queries as a single transaction.

Transactions become useful, for example, when the work is spread across multiple methods that each take responsability for their own part of it, including their own SaveChangesAsync . Then, either you explicitly commit the transaction eventually, or you dispose of its object, causing it to be rolled back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM