CodexBloom - Programming Q&A Platform

C# - implementing Multiple DbContexts in Entity Framework Core 6 When Using Transactions

👀 Views: 26 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
c# entity-framework ef-core database transactions C#

I'm upgrading from an older version and I've tried everything I can think of but I've searched everywhere and can't find a clear answer... I'm working with a question when trying to use multiple `DbContext` instances in a single transaction with Entity Framework Core 6. I have two `DbContext` classes, `AppDbContext` and `AuditDbContext`, and I'm trying to insert data into both databases within a single transaction. However, I am running into a `DbUpdateConcurrencyException` when trying to save changes, and it seems like the transaction isn't being managed properly across both contexts. Here is a simplified version of my code: ```csharp using (var transaction = await _context.Database.BeginTransactionAsync()) { try { var user = new User { Name = "John" }; _appDbContext.Users.Add(user); await _appDbContext.SaveChangesAsync(); var auditEntry = new AuditLog { Action = "User Created", UserId = user.Id }; _auditDbContext.AuditLogs.Add(auditEntry); await _auditDbContext.SaveChangesAsync(); await transaction.CommitAsync(); } catch (DbUpdateConcurrencyException ex) { // Handle concurrency issues here await transaction.RollbackAsync(); Console.WriteLine(ex.Message); } catch (Exception ex) { await transaction.RollbackAsync(); Console.WriteLine(ex.Message); } } ``` Despite wrapping the operations in a transaction, it seems like both contexts are not preserving the transaction state, leading to the `DbUpdateConcurrencyException`. I've also checked that there are no conflicting updates in the database and that the entities are being tracked correctly. I've tried using a `TransactionScope` as an alternative, but I ran into issues related to ambient transactions and performance. Is there a recommended approach for handling transactions across multiple `DbContext` instances? Am I missing something in the transaction handling or configuration? Any insights would be greatly appreciated! Any ideas what could be causing this? I recently upgraded to C# 3.9. Is this even possible? For reference, this is a production desktop app.