Home > database >  EF Core transaction lifetime
EF Core transaction lifetime

Time:07-30

We are using our select statement inside transaction scope because of concurrency concerns. The question is, if I put my transaction in using statement, do I still have to call Commit() method explicitly to be sure that the transaction is closed or Dispose() method will do the job?

Here's example code:

await using (var transaction = await Context.BeginTransactionAsync())
            {
                callbackUrl = await this.SomeRepository.GetResultAsync(request);
                await transaction.CommitAsync();
            }

CodePudding user response:

using is only calling a Dispose() method at the end. It will not Commit the transaction automatically.

Disposing also rolls back all the changes made within transaction. If you dispose before commit or just dispose it will roll back all the changes and close the transaction.

If there are no changes you don't have to commit the transaction to close it. You can just wait for the using to do it's job and dispose the transaction which will close it anyway.

Generally if you don't expect anything to be commited just don't use commit.

CodePudding user response:

The official docs would be your best friend in such situations.

Once you choose handle transactions manually, you should call commit or rollback in your program flow.

EFCore's transaction already have an atomic behavior for the SaveChanges method: it will commit it's implicit transaction changes if everything succeed and rollback on any error occurrence.

On a first sight of your code, there is no need to call commit (or even use transaction) once you are not making any changes to database, its just a query. I bet you are using this like a to change the context's query isolation level, is that right?

Maybe you should elaborate a little bit more of your context and the 'concurrency concerns' to get a more effective help.

  • Related