Entity Framework Core Migrations
Database migrations let you evolve your database schema over time while preserving existing data. This guide walks you through creating, applying, and managing migrations in an ASP.NET Core project.
1️⃣ Add the EF Core Tools
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-ef
2️⃣ Create Your First Migration
After defining your DbContext and entity classes, run:
dotnet ef migrations add InitialCreate
3️⃣ Apply the Migration
Use dotnet ef database update to apply pending migrations to the database.
dotnet ef database update
4️⃣ Common Scenarios
- Add a new column: add the property to the entity, then run
dotnet ef migrations add AddNewColumn. - Rename a column: use
RenameColumnin a custom migration for zero‑downtime. - Remove a column: delete the property, create a migration, and optionally add a default value.
5️⃣ Managing Migration History
EF Core stores migration history in the __EFMigrationsHistory table. You can view it with:
dotnet ef migrations list
💡 Tips & Best Practices
- Commit migration files to source control.
- Never edit a migration after it’s been applied to production.
- Separate schema changes from data migrations for clarity.
- Use
dotnet ef migrations scriptto generate SQL scripts for CI/CD pipelines.
📚 Further Reading
Explore more advanced topics: