EF Core Migrations
Note: EF Core Migrations is a powerful feature that allows you to manage your database schema as it evolves with your application.
Introduction to EF Core Migrations
EF Core Migrations provides a way to incrementally update your database schema to keep it synchronized with your model changes. Migrations are stored as code, allowing for version control and predictable schema evolution.
When you make changes to your entity classes or DbContext
, EF Core can generate a migration that represents these changes.
This migration is then applied to your database.
Key Concepts
- Migrations: Represent a set of changes to your database schema. They are code files that EF Core executes.
-
DbContext
: The central class that represents a session with the database and allows you to query and save data. -
IMigrationsAssembly
: Manages the discovery and loading of migrations. -
IMigrationsIdGenerator
: Generates unique identifiers for migrations. - Provider: The database provider (e.g., SQL Server, PostgreSQL, SQLite) handles the actual schema manipulation.
Getting Started with Migrations
1. Install the EF Core Tools
You'll need the EF Core tools installed. The most common way is via the NuGet Package Manager Console or the .NET CLI.
# Using .NET CLI
dotnet tool install --global dotnet-ef
# Or for a specific project (recommended)
dotnet add package Microsoft.EntityFrameworkCore.Design
2. Enable Migrations in your Project
From your project directory, run the following command to scaffold your first migration. EF Core will inspect your DbContext
and model to create the initial migration.
dotnet ef migrations add InitialCreate
This command creates a Migrations
folder in your project, containing two files:
-
A timestamped C# file (e.g.,
20231027123456_InitialCreate.cs
) containing theUp()
andDown()
methods to apply and revert the migration. -
A snapshot file (e.g.,
YourDbContextModelSnapshot.cs
) representing the current state of your model.
3. Apply the Migration to your Database
Once you have created a migration, you need to apply it to your database.
dotnet ef database update
This command executes the Up()
method of all pending migrations against your configured database.
Common Migration Commands
-
dotnet ef migrations add <MigrationName>
: Creates a new migration file. -
dotnet ef migrations list
: Shows pending and applied migrations. -
dotnet ef migrations remove
: Reverts the last migration and removes its files. -
dotnet ef database update [<TargetMigration>]
: Applies migrations to the database up to the specified migration (or the latest if not specified). -
dotnet ef database drop
: Drops the entire database. Use with extreme caution.
Working with Migrations
Generating Migrations
After changing your entity models or DbContext
, you need to generate a new migration to reflect these changes.
dotnet ef migrations add AddUserEmailColumn
Customizing Migrations
The generated migration files can be edited to customize the schema changes. The Up()
method defines how to apply changes, and the Down()
method defines how to revert them.
public partial class AddUserEmailColumn : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Email",
table: "Users",
type: "nvarchar(max)",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Email",
table: "Users");
}
}
Handling Complex Changes
For more complex schema operations that might not be directly supported by EF Core's fluent API or data annotations, you can use raw SQL commands within your migration's Up()
and Down()
methods.
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("CREATE TRIGGER MyTrigger ON dbo.MyTable AFTER INSERT AS BEGIN -- ... END");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DROP TRIGGER MyTrigger");
}
Best Practices
- Keep Migrations Small: Each migration should represent a single logical change to the database schema.
- Test Migrations: Always test your migrations in a development or staging environment before applying them to production.
- Version Control: Commit your migration files to your version control system along with your application code.
-
Use the
Down()
Method: Ensure yourDown()
methods are well-defined to allow for easy rollback. - Avoid Manual Database Changes: Once you start using migrations, try to manage all schema changes through them to maintain consistency.
Tip: Consider using the --verbose
flag with EF Core CLI commands for more detailed output, which can be helpful for debugging.
Warning: When running dotnet ef database update
in production, ensure you have a backup of your database.