CodexBloom - Programming Q&A Platform

ASP.NET Core 3.1 - How to handle multiple DbContexts in a single project?

πŸ‘€ Views: 12 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
asp.net-core ef-core dbcontext csharp

I'm a bit lost with I'm currently developing an ASP.NET Core 3.1 application where I need to manage two different DbContexts, `AppDbContext` and `IdentityDbContext`... I have configured them in the `Startup.cs` class like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection"))); services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<IdentityDbContext>() .AddDefaultTokenProviders(); } ``` The issue arises when I try to use both contexts within a single service. Here’s an example of how I’m trying to inject them into a service: ```csharp public class MyService { private readonly AppDbContext _appDbContext; private readonly IdentityDbContext _identityDbContext; public MyService(AppDbContext appDbContext, IdentityDbContext identityDbContext) { _appDbContext = appDbContext; _identityDbContext = identityDbContext; } public async Task DoSomethingAsync() { // Some logic using both contexts } } ``` However, I’m encountering an `InvalidOperationException` with the message: "A second operation started on this context before a previous operation completed." This happens when I try to call `DoSomethingAsync()` from a controller action that also performs a database operation using one of the contexts. I’ve read that this can happen if multiple operations are attempted concurrently on the same context, and I suspect that the way I'm managing the services might be contributing to this. To troubleshoot, I attempted to make sure all database calls within a single method are awaited properly, and I even tried using separate `DbContext` instances, but I still see the same error. Is there a best practice for using multiple `DbContexts` in a single service, or am I missing something fundamental in my configuration? Any advice or alternative patterns that could help resolve this would be greatly appreciated! Is there a better approach? This is part of a larger microservice I'm building. I appreciate any insights!