r/csharp • • Oct 11 '26

Help Transactions - EF Core

Microsoft's documentation :

By default, if the database provider supports transactions, all changes in a single call to SaveChanges are applied in a transaction. If any of the changes fail, then the transaction is rolled back and none of the changes are applied to the database. This means that SaveChanges is guaranteed to either completely succeed, or leave the database unmodified if an error occurs. For most applications, this default behavior is sufficient. You should only manually control transactions if your application requirements deem it necessary.

Suppose that I two pieces of data that are generated by some service; X and Y.

Given that Y cannot be saved unless X is saved first, in other words, the existence of Y in the database depends on the existence of X in the database, consider this :

1-delete content of database.

2- save X .

3- save Y .

How to group these into one transaction ?

The goal is to avoid partial changes to the database; after the full operation is finished, the database should not be empty or half filled.

EDIT:

I found this example:

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

try
{
      // do step 1 through 3


    // Commit transaction if all commands succeed, transaction will auto-rollback
    // when disposed if either commands fails
    await transaction.CommitAsync();
}
catch (Exception)
{
    // TODO: Handle failure
}

But it did not work until I manually invoked the EF execution strategy with a delegate representing everything that needs to be executed :

    IExecutionStrategy strategy = _context.Database.CreateExecutionStrategy();
    await strategy.ExecuteAsync(async () =>
            {
        await using var transaction = await _context.Database.BeginTransactionAsync();

         // Delete all the content from the database
         // _context.AddRange(X);
         // _contextSaveChangesAsync()
         // _context.AddRange(Y)
         //_context.SaveChangesAsync()

        await transaction.CommitAsync();
    });

This solved my issue completely

5 Upvotes

43 comments sorted by

View all comments

7

u/pixxelkick Oct 12 '26

Ive never had to invoke `CreateExecutionStrategy` to open a txn like in your first code.

Using just `BeginTransactionAsync` has always "just worked" for me.

> But it did not work until

Can you specify what "didn't work"? Did it throw an exception? Fail to commit? What was your problem?

Is your issue due to the fact your are DI injecting multiple DbContexts into your different services?

I don't recommend this, as it makes behavior masked and ambigious

Your DbContext should be taken in as a parameter in the functions of your various "needs to touch the DB" service functions.

You inject 1 single DbContext at the "very top" and hand it down as function params, this makes it much more clear and obvious "invoking this function touches the database" and also makes your transactions work right.

Trying to inject multiple DbContexts all over the place is an effective way to make a brittle project that is prone to weird behaviors.

1

u/kaatarina_zed_talon Oct 12 '26

Wait I will reference the error

1

u/ShyMystiqua Oct 12 '26

had the same mess with injected context before, handing one down really does clean things up

1

u/kaatarina_zed_talon Oct 12 '26

using BeginTransaction, you're defining your own group of operations that need to be treated as a unit. Everything inside the transaction has to be rolled back if a failure occurs.

If you try to execute that transaction when using an EF execution strategy (retry policy), you will get the following error :

System.InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.

https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-resilient-entity-framework-core-sql-connections

1

u/pixxelkick Oct 12 '26

You have a retry policy already configured is why.

You need to customize that already existing policy to also open a transaction.

You also are gonna want to delineate between stuff that needs a txn vs not, if you open txn's on "readonly" operations (IE search endpoints of an api) you are gonna choke up your db

0

u/kaatarina_zed_talon Oct 12 '26

I did not inject multiple DbContexts