Skip to content

EF Core Migrations

This project uses EF Core 6 with two DbContext classes:

Context Schema Project path
CoreDbContext msort src/distribution-management-server-layered/Core/Persistence/
MeeshoDbContext meesho src/distribution-management-server-layered/Persistence/

Apply all pending migrations

make migrate
# or:
bash scripts/migrate.sh

This applies pending migrations for both contexts in order and prints a summary of applied migrations.


Add a new migration

export DOTNET_ROOT="$HOME/.dotnet" && export PATH="$DOTNET_ROOT:$DOTNET_ROOT/tools:$PATH"

dotnet ef migrations add DescriptiveMigrationName \
  --context CoreDbContext \
  --project src/distribution-management-server-layered \
  --startup-project src/distribution-management-server-layered
export DOTNET_ROOT="$HOME/.dotnet" && export PATH="$DOTNET_ROOT:$DOTNET_ROOT/tools:$PATH"

dotnet ef migrations add DescriptiveMigrationName \
  --context MeeshoDbContext \
  --project src/distribution-management-server-layered \
  --startup-project src/distribution-management-server-layered

Then apply:

make migrate


The Designer.cs requirement

Always commit the .Designer.cs file

EF Core discovers migrations by scanning for the [Migration("id")] and [DbContext(...)] attributes. These live exclusively in the .Designer.cs companion file.

If you create a migration .cs file manually (without dotnet ef migrations add), EF will not detect it — dotnet ef migrations list will show it as missing.

Rule: Every YourMigration.cs must have a companion YourMigration.Designer.cs. The dotnet ef migrations add command creates both automatically. Never commit one without the other.

File pair required:

20260608121000_AddRelationalForeignKeys.cs           ← the migration
20260608121000_AddRelationalForeignKeys.Designer.cs  ← EF discovery + model snapshot


Check migration status

make migrate-status
# or:
PGPASSWORD='3edc#EDC' psql -U postgres -d "dms-layered" \
  -t -c 'SELECT "MigrationId" FROM public."__EFMigrationsHistory" ORDER BY 1;'

Revert a migration (development only)

export DOTNET_ROOT="$HOME/.dotnet" && export PATH="$DOTNET_ROOT:$DOTNET_ROOT/tools:$PATH"

# Roll back to the previous migration:
dotnet ef database update PreviousMigrationName \
  --context CoreDbContext \
  --project src/distribution-management-server-layered

# Remove the last generated migration file (only if not yet committed):
dotnet ef migrations remove \
  --context CoreDbContext \
  --project src/distribution-management-server-layered

Never revert applied migrations in production

Rolling back a migration in production requires careful coordination. See Rollback Procedure.


Migration naming convention

Use PascalCase describing what the migration adds or changes:

✅ AddClientBinConfigTables
✅ EnforceSingleActiveSession
✅ AddRelationalForeignKeys
✅ UpdateDataSyncRejectedFieldToString

❌ Fix
❌ Update1
❌ Migration20260618