EF Core Migrations
Database migrations are a powerful feature of Entity Framework Core (EF Core) that allow you to evolve your database schema over time as your application's model changes. Migrations provide a way to systematically manage schema changes, ensuring that your database stays in sync with your code.
What are Migrations?
When you make changes to your EF Core model (e.g., adding a new entity, adding a property to an existing entity, or changing a relationship), you need to update your database schema to reflect these changes. Migrations translate these model changes into code that can create or alter database objects like tables, columns, and constraints.
Key Concepts
- Migrations: These are files that represent incremental changes to your database schema. Each migration contains code to apply the schema change (
Up
method) and code to revert it (Down
method). - Model Snapshot: EF Core takes a snapshot of your current model. When you generate a new migration, EF Core compares the current model to the latest model snapshot to determine what has changed and generate the necessary C# code for the migration.
- Provider: EF Core uses a database provider (e.g., SQL Server, PostgreSQL, SQLite) to translate the migration operations into the specific SQL commands understood by that database.
Common Migration Operations
Generating a New Migration
To create a new migration, you typically use the EF Core .NET CLI or Package Manager Console commands. First, ensure you have the EF Core tools installed.
Using .NET CLI:
dotnet ef migrations add InitialCreate
dotnet ef migrations add AddProductDescription
Using Package Manager Console:
Add-Migration InitialCreate
Add-Migration AddProductDescription
Applying Migrations
Once you've generated migrations, you need to apply them to your database. This updates the database schema to match your model.
Using .NET CLI:
dotnet ef database update
dotnet ef database update InitialCreate
Using Package Manager Console:
Update-Database
Update-Database InitialCreate
Reverting Migrations
If you need to roll back to a previous state of your database, you can use the Down
method of a migration.
Using .NET CLI:
dotnet ef migrations remove
dotnet ef migrations remove AddProductDescription
Using Package Manager Console:
Remove-Migration
Remove-Migration AddProductDescription
To revert a specific migration:
Using .NET CLI:
dotnet ef database update [TargetMigrationName]
Using Package Manager Console:
Update-Database [TargetMigrationName]
Customizing Migrations
Sometimes, EF Core's automatic generation might not be sufficient. You can manually edit the generated migration files to perform custom operations. You can also use the migrationBuilder.Sql()
method to execute raw SQL commands.
Example of Custom SQL in a Migration
public override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "MyCustomTable",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_MyCustomTable", x => x.Id);
});
// Execute custom SQL
migrationBuilder.Sql("INSERT INTO SomeOtherTable (Data) VALUES ('Initial Seed Data')");
}
public override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM SomeOtherTable WHERE Data = 'Initial Seed Data'");
migrationBuilder.DropTable(
name: "MyCustomTable");
}
Best Practices
- Generate migrations early and often: Don't let schema changes accumulate.
- Keep migrations small and focused: Each migration should represent a single logical change.
- Test migrations thoroughly: Apply them to development and staging environments before production.
- Review generated code: Ensure the migrations do exactly what you intend.
- Add comments to migrations: Explain complex or custom operations.
Related API References
By mastering EF Core migrations, you can confidently manage your database schema alongside your application code, leading to more robust and maintainable applications.