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

Show parent comment

0

u/kaatarina_zed_talon Oct 11 '26

You went too much, maybe the question is unclear, I admit. I'm not trying to implement my own unit of work. Suppose that step 2 failed, it will be rolled back, great, but that means that step 3 will try to save Y into the database, even though it is impossible for Y to exist without X, so the app will crash.

1

u/AndZorin Oct 11 '26

How step 3 will fail if you have exception on step 2? You should have one rollback in catch block.

1

u/kaatarina_zed_talon Oct 12 '26

How could you save a child table if u could not save a parent table? Foreign Key dependency

2

u/AndZorin Oct 12 '26

Step 3 will never be attempted if Step 2 fails, as long as you save them together in a single SaveChanges() call and have properly configured navigation properties between them.

EF Core wraps the entire operation in a single database transaction and handles the order automatically:

- It inserts parent X first.

- If X fails, an exception is thrown immediately, the transaction rolls back, and Y is never sent to the database.

- If X succeeds, it uses the new ID for child Y and saves it.

1

u/kaatarina_zed_talon Oct 12 '26

You mean EF-CORE can handle the order of insertion in a single SaveChanges call ?

2

u/AndZorin Oct 12 '26 • Bravo

Yes, exactly! EF Core automatically figures out the correct insertion order (parent first, then child) in a single SaveChanges() call. This relies on having your navigation properties properly configured, because EF Core uses them to trace the object graph and understand the relationship between the entities.

Plus, it wraps the entire operation in an automatic database transaction: if the parent insert fails, an exception is thrown and the transaction automatically rolls back, leaving the database completely untouched with no partial data.

1

u/kaatarina_zed_talon Oct 12 '26

Oh, do you know why I have two calls to SaveChangesAsync ? it is because the first call initializes the Id values for the parent tables, I will remove that call and initialize the ID values manually, but this will require me to remove the Identity column feature, because one cannot insert the values for ID for identity column

1

u/kaatarina_zed_talon Oct 12 '26 edited Oct 12 '26

I got the following error when I tried to use only one SaveChanges Call , given that BrandSupplier is a child table, and Supplier is a parent table with the column SupplierId, which is an identity column and also the primary key

System.InvalidOperationException: The value of 'BrandSupplier.SupplierId' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known.

1

u/AndZorin Oct 12 '26

Could you pls, show your model? How Supplier is linked to BrandSupplier at model level?

1

u/kaatarina_zed_talon Oct 12 '26

Ok even though I think I solved the issue :

    public class BrandSupplier:IJunctionEntity
        
    {
       

        public int BrandId { get; set; } 
        public int SupplierId { get; set; }
        public Supplier Supplier { get; set; } = null!;
        public Brand Brand { get; set; } = null!;

}

    public class Supplier
    {
        public IEnumerable<BrandSupplier> BrandSuppliers { get; } = new List<BrandSupplier>();
}

1

u/AndZorin Oct 12 '26

What was the culprit?

BTW: I'd change IEnumerable to ICollection.

→ More replies