0

I am using a transaction and want to learn to commit inner commit?

        await using var transaction = await _context.Database.BeginTransactionAsync();

        try
        {
            // update table 1

            // update table 2

            await _context.SaveChangesAsync(); // necessary to use this???
            await transaction.CommitAsync();   // necessary to use this???

        }
        catch (Exception)
        {
            await transaction.RollbackAsync();

            throw;
        }

Should I use commit transaction after await _context.SaveChangesAsync();. My entity framework version is core 3.0.

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • If the same dbcontext is the only participant to a transaction then you don't t need a transaction at all. SaveChanges will wrap all the resulting statements in a transaction. – StuartLC Nov 15 '19 at 08:22
  • table 1 and table 2 is in same db context, so should not I use transaction? – barteloma Nov 15 '19 at 08:51
  • Yes, no need to wrap in a transaction as long as you only call `SaveChanges` once, and as long as you are using the same DbContext instance. Your updates to table1 and table2 only 'occur' during the SaveChanges. See also https://stackoverflow.com/a/6028691/ – StuartLC Nov 15 '19 at 09:33
  • Little late, but in this case: Could .SaveChangesAsync be omitted and the updates would still be saved on commit? – Radall Apr 26 '21 at 07:33

0 Answers0