Entity Framework
EF Migrations
Multiple Contexts
Database Configuration
.NET Development

How do I enable EF migrations for multiple contexts to separate databases?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Entity Framework Core can manage migrations for multiple DbContext classes, even when each context points to a different database. The key is to keep each context's configuration and migration history separate.

In practice, that means three things: separate connection strings, separate migration folders, and migration commands that explicitly name the target context. Once those pieces are in place, EF Core handles the rest cleanly.

Register Each Context with Its Own Connection String

Start by configuring each context to use a different database:

csharp
1using Microsoft.EntityFrameworkCore;
2
3var builder = WebApplication.CreateBuilder(args);
4
5builder.Services.AddDbContext<CatalogDbContext>(options =>
6    options.UseSqlServer(builder.Configuration.GetConnectionString("CatalogDb")));
7
8builder.Services.AddDbContext<IdentityDbContext>(options =>
9    options.UseSqlServer(builder.Configuration.GetConnectionString("IdentityDb")));

And in appsettings.json:

json
1{
2  "ConnectionStrings": {
3    "CatalogDb": "Server=.;Database=CatalogDb;Trusted_Connection=True;TrustServerCertificate=True",
4    "IdentityDb": "Server=.;Database=IdentityDb;Trusted_Connection=True;TrustServerCertificate=True"
5  }
6}

Each context should represent its own model boundary. If two contexts share the same tables carelessly, migration management becomes much harder.

Create Separate Migration Sets

When you add migrations, tell EF Core which context you mean and store the generated files in different folders:

bash
1dotnet ef migrations add InitialCatalog \
2  --context CatalogDbContext \
3  --output-dir Migrations/Catalog
4
5dotnet ef migrations add InitialIdentity \
6  --context IdentityDbContext \
7  --output-dir Migrations/Identity

This separation matters. Without it, migration files from different contexts end up mixed together, which becomes confusing fast and can lead to the wrong snapshot being updated.

Apply them separately too:

bash
dotnet ef database update --context CatalogDbContext
dotnet ef database update --context IdentityDbContext

Each database gets only the migrations that belong to its own context.

Make Design-Time Creation Reliable

The CLI needs to construct each context at design time. If your application setup is simple, the default startup path may work. If not, add design-time factories.

csharp
1using Microsoft.EntityFrameworkCore;
2using Microsoft.EntityFrameworkCore.Design;
3
4public class CatalogDbContextFactory : IDesignTimeDbContextFactory<CatalogDbContext>
5{
6    public CatalogDbContext CreateDbContext(string[] args)
7    {
8        var options = new DbContextOptionsBuilder<CatalogDbContext>()
9            .UseSqlServer("Server=.;Database=CatalogDb;Trusted_Connection=True;TrustServerCertificate=True")
10            .Options;
11
12        return new CatalogDbContext(options);
13    }
14}

Create a similar factory for the other context if needed. This avoids CLI errors such as "Unable to create an object of type ..."

Keep Migration History Separate

By default, each database will maintain its own __EFMigrationsHistory table. That is fine when the contexts point to different databases, which is your scenario here.

The important point is conceptual: migrations belong to the context that produced them. Do not mix migration files or apply one context's migration set to another database just because the provider is the same.

A Practical Workflow

A clean workflow for ongoing development looks like this:

  1. change models in CatalogDbContext
  2. run dotnet ef migrations add ... --context CatalogDbContext
  3. update only the catalog database
  4. repeat independently for IdentityDbContext

This keeps each schema evolution path predictable. You can deploy one database change without forcing an unrelated migration in the other context.

Common Pitfalls

  • Forgetting --context on CLI commands. EF Core may pick the wrong context or fail when multiple exist.
  • Writing all migrations into one folder. The generated snapshots then become hard to manage.
  • Assuming one startup configuration can always create every context at design time. Use IDesignTimeDbContextFactory when the CLI needs help.
  • Letting contexts overlap on table ownership without a clear boundary.
  • Applying database update blindly and assuming both databases moved forward the same way.

Summary

  • Use a separate connection string for each DbContext.
  • Generate migrations with --context and separate output directories.
  • Update each database independently.
  • Add design-time factories when the EF CLI cannot build a context cleanly.
  • Treat each context as its own migration stream, not as one shared schema history.

Course illustration
Course illustration

All Rights Reserved.