CodexBloom - Programming Q&A Platform

InvalidOperationException When Using Entity Framework Core with Multiple DbContext Instances in .NET 6

πŸ‘€ Views: 84 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
entity-framework-core dotnet-6 dbcontext C#

I keep running into I've looked through the documentation and I'm still confused about I'm working on a personal project and I'm working with an `InvalidOperationException` when trying to perform operations with multiple `DbContext` instances in my .NET 6 application... The behavior message reads: "The instance of entity type 'Product' want to be tracked because another instance with the same key value for {'Id'} is already being tracked." I have two `DbContext` instances: `AppDbContext` and `LoggingDbContext`, and I'm trying to fetch data from `AppDbContext`, modify it, and then log some information in `LoggingDbContext` within the same method. Here’s a simplified version of what I’m doing: ```csharp public async Task UpdateProductAndLog(int productId, string logMessage) { using (var appContext = new AppDbContext()) { var product = await appContext.Products.FindAsync(productId); if (product != null) { product.Price += 10; // Update product price await appContext.SaveChangesAsync(); } } using (var loggingContext = new LoggingDbContext()) { var logEntry = new LogEntry { Message = logMessage, CreatedAt = DateTime.UtcNow }; loggingContext.LogEntries.Add(logEntry); await loggingContext.SaveChangesAsync(); } } ``` I thought that creating separate instances of `DbContext` would prevent tracking issues, but it seems like the `Product` entity is being tracked by both contexts. I've also tried detaching the entity before modifying it but that didn't resolve the scenario. Am I missing something in terms of `DbContext` lifecycle management? How can I properly handle updates and logging without running into this tracking scenario? I'm working on a service that needs to handle this. Is there a better approach? For context: I'm using C# on Windows. Thanks in advance! For reference, this is a production web app. What am I doing wrong?