Skip to content Skip to footer

Organising EF Core Migrations with Multiple DbContexts

This project uses three separate DbContexts, each with its own database and its own migration folder. This guide explains how the setup works and how to work with migrations safely as a developer.


Why Multiple DbContexts?

We split the application into three contexts:

ContextFolderPurpose
DBAuthContextMigrations/AuthIdentity, roles, organisations
DBContextMigrations/CoreMain app data (patients, sessions, documents, etc.)
DBDataVaultContextMigrations/DataVaultData vault / analytics tables

Each context has its own connection string and its own __EFMigrationsHistory table. Migrations for one context never touch another database.


Folder Names: Auth, Core, DataVault (Not the Context Names)

We use Auth, Core, and DataVault as folder names, not DBAuthContext, DBContext, or DBDataVaultContext.

Reason: namespace conflict.
EF generates a C# namespace from the folder path, e.g. core.Migrations.Auth. The generated code includes:

[DbContext(typeof(DBAuthContext))]

If the folder were named DBAuthContext, the namespace would be core.Migrations.DBAuthContext. The compiler would then treat DBAuthContext in the attribute as the namespace, not the type, and you get:

CS0118: 'DBAuthContext' is a namespace but is used like a type

By using Auth, Core, and DataVault, the namespace and the context type name don’t clash, so the project builds without extra fixes.

Rule of thumb: migration folder name ≠ DbContext type name; use a short, conflict-free name.


Folder Layout

Migrations/
├── Auth/                    ← DBAuthContext
│   ├── 20260216122644_InitialAuth.Designer.cs
│   └── DBAuthContextModelSnapshot.cs
├── Core/                    ← DBContext
│   ├── 20260216120853_InitialCore.Designer.cs
│   └── DBContextModelSnapshot.cs
├── DataVault/               ← DBDataVaultContext
│   ├── 20260217092702_InitialDataVault.cs
│   ├── 20260217092702_InitialDataVault.Designer.cs
│   └── DBDataVaultContextModelSnapshot.cs
└── README.md                ← this file
  • One folder per context.
  • Each folder has a model snapshot (*ModelSnapshot.cs) and one or more migrations (.cs + .Designer.cs).
  • Don’t put migrations in the root Migrations/ folder; they belong in the correct subfolder.

Adding a New Migration

Day-to-day: no --output-dir needed.
EF puts new migrations in the same folder as the existing snapshot for that context. So you only need:

cd backend/core

dotnet ef migrations add "<MigrationName>" --context <ContextName>

Examples:

dotnet ef migrations add "AddUserDisplayName" --context DBAuthContext
dotnet ef migrations add "AddSessionNotesIndex" --context DBContext
dotnet ef migrations add "AddDataVaultTable" --context DBDataVaultContext

The new migration is created in Migrations/Auth, Migrations/Core, or Migrations/DataVault automatically, and the generated namespace stays correct (no manual fixes).

First time only (new context / empty folder):
When adding the very first migration for a context and the subfolder does not exist yet, you must pass --output-dir so EF creates the folder and puts the snapshot there:

dotnet ef migrations add "InitialDataVault" --context DBDataVaultContext --output-dir Migrations/DataVault

After that, all later migrations for that context can use the short form without --output-dir.


Applying Migrations (What Happens at Startup)

Migrations are applied automatically when the app runs. In Program.cs we call:

  • DBAuthContext.Database.MigrateAsync()
  • DBDataVaultContext.Database.MigrateAsync()
  • DBContext.Database.MigrateAsync() (via the context factory)

So you don’t run dotnet ef database update in production; the app applies pending migrations on startup. Locally you can still use dotnet ef database update --context <ContextName> if you want to apply without starting the full app.


Removing a Migration

Only remove the last migration for a context (the one not yet applied to the DB, or the one you’re happy to roll back).

cd backend/core
dotnet ef migrations remove --context DBAuthContext
# or DBContext, or DBDataVaultContext

This:

  1. Connects to the database to check applied migrations.
  2. If the last migration is applied, it will refuse unless you use --force (which will also revert the DB).
  3. Deletes the last migration files and updates the snapshot.

If the database is unavailable (e.g. no Docker), remove will fail. In that case you can delete the migration .cs and .Designer.cs files by hand; the snapshot may still reference that migration, so prefer remove when the DB is reachable.


Rules to Follow

  1. One context per migration. When adding a migration, pick exactly one context and one folder.
  2. Use --output-dir only for the first migration of a context (when creating the subfolder). After that, dotnet ef migrations add "Name" --context X is enough; EF uses the snapshot’s folder.
  3. Don’t rename migration folders to the context type name (DBAuthContext, DBContext, DBDataVaultContext); that reintroduces the namespace/type conflict.
  4. Don’t edit the snapshot by hand. Let EF generate and update it when you add/remove migrations.
  5. Don’t delete or reorder migrations that have already been applied in shared or production databases; that breaks migration history.

Quick Reference

TaskCommand
Add migration (any context)dotnet ef migrations add "YourName" --context DBAuthContext (or DBContext / DBDataVaultContext)
First migration for a contextdotnet ef migrations add "InitialX" --context X --output-dir Migrations/Auth (or Core / DataVault)
Remove last migrationdotnet ef migrations remove --context <ContextName>
List pending migrationsdotnet ef migrations list --context <ContextName>
Apply migrations (DB only)dotnet ef database update --context <ContextName>

All dotnet ef commands must be run from backend/core (the project that contains the DbContexts and the Migrations folder).


Troubleshooting

Build error: “DBAuthContext is a namespace but is used like a type”
You have a migration (or snapshot) in a folder whose name matches the context type, so the generated namespace clashes. Move the migration into the correct folder (Auth, Core, or DataVault) and fix the namespace in the migration/snapshot to match that folder (e.g. core.Migrations.Auth). Or regenerate the migration in the correct folder and remove the wrong one.

Migration was created in Migrations/ (root) instead of a subfolder
Usually this means the snapshot for that context is missing from the subfolder (e.g. the first migration was never created with --output-dir). Ensure Migrations/Auth, Migrations/Core, or Migrations/DataVault contains the snapshot for that context. Then remove the wrongly placed migration and run dotnet ef migrations add "Name" --context X again; it should land in the correct subfolder.

“Connection refused” or “Resource temporarily unavailable” when running migrations remove
The EF tools need to connect to the database. Start your DB (e.g. make up or Docker) and try again, or remove the migration files manually if you understand the implications.

Wrong context when adding a migration
Always pass the correct context: DBAuthContext, DBContext, or DBDataVaultContext. If you added a migration for the wrong context, remove it (migrations remove) and add a new one with the correct context and output folder.

Leave a Comment