Performance in transaction with Entity Framework Core transactions

461 views Asked by At

I have the following EF steps (regular ASP.NET MVC application):

A separate method:

   async Task Action(...)
   {
      using (var ctx = await _ctxFactory.CreateDbContextAsync())
      using (var trx = await ctx.Database.BeginTransactionAsync())
      {
          await ctx.Table1.AddAsync(...);
          await ctx.Table2.AddRangeAsync(...);  // big number of records

          await ctx.SaveChangesAsync();
      }
   }

Run this method from different threads at the same time.

I wonder from a performance point of view, does it make sense (for both success and rollback paths) to additionally call SaveChangesAsync after "inserting" records into Table1 and before adding records to Table2? I don't think so, but wonder whether I'm missing something.

2

There are 2 answers

0
David Browne - Microsoft On BEST ANSWER

It won't increase the number of round trips to the database or increase the cost in any way. But neither will it help.

It's sometimes necessary to call SaveChanges multiple times to retrieve database-generated values, to avoid circular dependencies, or to manage the number of tracked entities, but otherwise there's no reason to call SaveChanges multiple times in a transaction.

1
Vivek Nuna On

No, you don't need it, EF will have a track of entities within the transaction. Calling the SaveChangesAsync will unnecessarily increase the DB roundtrips. If you still want multiple SaveChangesAsync move them to different transactions.