CodexBloom - Programming Q&A Platform

How to handle multiple DbContext instances in ASP.NET Core using Entity Framework Core?

πŸ‘€ Views: 10 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-04
asp.net-core entity-framework-core dbcontext C#

I'm currently working on an ASP.NET Core 6.0 application using Entity Framework Core 6.0. My application requires handling multiple databases, and I've set up different `DbContext` classes for each database. However, I'm working with issues when trying to save changes to a context that has been resolved through dependency injection. It seems like the changes aren't being saved, and I receive the behavior: `System.InvalidOperationException: The instance of entity type 'EntityName' want to be tracked because another instance with the same key value for {'Id'} is already being tracked.` I've tried using a separate scope for each `DbContext`, ensuring that I dispose of the contexts properly, but the scenario continues. Here is the code snippet I have: ```csharp public class MyService { private readonly DbContextA _contextA; private readonly DbContextB _contextB; public MyService(DbContextA contextA, DbContextB contextB) { _contextA = contextA; _contextB = contextB; } public async Task<bool> SaveData(EntityType entity) { _contextA.Add(entity); return await _contextA.SaveChangesAsync() > 0; } } ``` In this setup, I'm injecting both `DbContextA` and `DbContextB` through the constructor, but it appears that changes to `EntityType` are conflicting due to tracking issues. I also considered using `AsNoTracking()` when fetching data, but that doesn’t seem to help in this case. Is there a recommended pattern or best practice for working with multiple `DbContext` instances that can help avoid these tracking conflicts? Any insights would be greatly appreciated! My development environment is Ubuntu. Has anyone else encountered this?