CLI Migrations & Schema Syncing

CLI Migrations & Schema Syncing in .NET: Migrations allow developers to update the database schema incrementally as the C# domain model evolves, without losing…

Migrations allow developers to update the database schema incrementally as the C# domain model evolves, without losing existing data.


1. Migration CLI Commands

# 1. Add a new migration after modifying an entity
dotnet ef migrations add AddLessonOrderIndex -o Data/Migrations

# 2. Inspect the generated migration file (Up and Down methods)
# Notice: 'Up' applies schema changes, 'Down' handles rollback

# 3. Apply all pending migrations to the database
dotnet ef database update

# 4. Generate idempotent SQL script for automated production release
dotnet ef migrations script --idempotent --output ./deploy-migrations.sql

2. Applying Migrations in Docker Containers

Never call context.Database.Migrate() on startup in multi-replica Kubernetes or cloud container deployments (concurrent migrations can deadlock the schema). Use generated SQL scripts or an init-container.