Entity Framework Core Migrations
EF Core Migrations is a feature that enables incremental data schema changes to your database as your model evolves. It is a purely code-based approach to schema management, allowing you to represent your model changes as C# or Visual Basic code.
This documentation covers the core concepts, common scenarios, and best practices for using EF Core Migrations.
Key Concepts
- Migrations: Represent incremental changes to your database schema.
DbContext
: The central class for interacting with the database.IMigrationsAssembly
: Responsible for loading and managing migrations.MigrationsSqlGenerator
: Generates SQL statements for migrations.
Getting Started with Migrations
1. Enabling Migrations
Before you can use Migrations, you need to enable them for your project. Open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console) and run the following command:
Enable-Migrations
This command creates a Migrations
folder in your project,
containing an initial migration file.
2. Creating a New Migration
Whenever you make a change to your EF Core model (e.g., adding a new entity, adding a new property to an entity, or changing relationships), you need to create a new migration to reflect that change in the database.
Use the following command in the Package Manager Console:
Add-Migration
Replace MigrationName
with a descriptive name for your migration
(e.g., AddUserTable
, UpdateProductPrice
).
3. Applying Migrations
Once you have created a migration, you can apply it to your database. This will execute the SQL statements defined in the migration file.
To update your database to the latest migration:
Update-Database
You can also specify a target migration:
Update-Database
Working with Migration Code
Each migration is a C# (or VB.NET) class that inherits from
. It has two main methods:
Migration
-
Up()
: This method is executed when you apply the migration. It contains the code to add or alter database objects. -
Down()
: This method is executed when you roll back the migration. It contains the code to undo the changes made in theUp()
method.
Example Migration Code
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourProject.Migrations
{
public partial class AddProductPrice : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<decimal>(
name: "Price",
table: "Products",
nullable: false,
defaultValue: 0m);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Price",
table: "Products");
}
}
}
Advanced Scenarios
- Custom SQL: Executing arbitrary SQL statements within migrations.
- Conditional Logic: Handling different database providers or environments.
- Data Migrations: Seeding or modifying data as part of migrations.
- Reverting Migrations: Rolling back to a previous state.
Custom SQL
You can execute raw SQL statements within your migrations using
. This is useful for operations
that cannot be expressed using the EF Core Migrations API.
migrationBuilder.Sql(...)
migrationBuilder.Sql("CREATE INDEX IX_Customer_LastName ON Customers (LastName);");
Conditional Logic
EF Core Migrations can generate different SQL for different database providers. You can also add conditional logic to your migration code if needed.
Data Migrations
To seed or update data as part of your schema changes, you can create
"data migrations". This involves overriding the
and
Up
methods to include data manipulation operations.
Down
Reverting Migrations
If you need to undo a migration, you can roll back to a specific migration or all migrations.
To revert to a previous migration:
Update-Database
To revert all migrations (effectively dropping all tracked schema changes):
Update-Database 0
Best Practices
- Keep migrations small and focused on a single logical change.
- Always write a corresponding
Down()
method for everyUp()
method. - Avoid modifying migration files after they have been applied to production databases.
- Use descriptive names for your migrations.
- Test your migrations thoroughly in development and staging environments.