Migrations with Entity Framework Core
Entity Framework Core (EF Core) Migrations is a powerful feature that enables you to incrementally develop your data model and deploy changes to your database schema. It allows you to evolve your database schema alongside your application's data model without losing existing data.
This document will guide you through the essential concepts and common scenarios of using EF Core Migrations.
What are Migrations?
Migrations are essentially versions of your data model. Each migration represents a step in evolving your schema from one version to the next. EF Core tracks which migrations have been applied to your database, allowing you to apply new migrations or roll back to previous ones.
Key aspects of migrations:
- Idempotent: Migrations are designed to be run multiple times without unintended side effects.
- Versioned: Each migration has a unique timestamp-based name (e.g.,
20230101000000_MyFirstMigration
) which indicates the order of application. - Code-based: Migrations are represented by C# classes, giving you full control over schema changes.
Creating Migrations
You typically create a migration when you make changes to your EF Core model (e.g., adding a new entity, property, or relationship). EF Core can automatically generate the code for these changes.
Use the following .NET CLI command in your project's directory:
dotnet ef migrations add InitialCreate
This command will create a new migration file in the Migrations
folder of your project. The file will contain two methods:
Up()
: Contains the code to apply the migration (e.g., create tables, add columns).Down()
: Contains the code to revert the migration (e.g., drop tables, remove columns).
For example, if you add a new entity Product
to your DbContext
:
public class MyDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
// ... other DbSets
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Running dotnet ef migrations add AddProductEntity
would generate code to create the Products
table in your database.
Applying Migrations
Once migrations are created, you need to apply them to your database. This is usually done at application startup.
Using the .NET CLI:
dotnet ef database update
This command applies all pending migrations to the target database. If the database doesn't exist, it will be created.
You can also apply migrations programmatically within your application's code:
using Microsoft.EntityFrameworkCore;
public class Program
{
public static void Main(string[] args)
{
var context = new MyDbContext(); // Assuming MyDbContext is configured
// Apply pending migrations
context.Database.Migrate();
// ... rest of your application logic
}
}
Generating SQL Scripts
Sometimes, you might want to generate SQL scripts that can be executed manually or by database administrators. This is particularly useful for deployment pipelines.
To generate a script for all pending migrations:
dotnet ef migrations script
To generate a script for a specific migration:
dotnet ef migrations script 20230101000000_InitialCreate
You can also specify a target migration to script up to:
dotnet ef migrations script --idempotent --target-migration 20230102000000_AddUserTable
Advanced Topics
- Custom Migrations: For complex scenarios not covered by EF Core's automatic generation, you can write custom migration code using
IMigrationCommandTreeGenerator
or by directly executing raw SQL. - Seeding Data: You can seed initial data into your database during the migration process.
- Reverting Migrations: Use
dotnet ef migrations remove
to remove the last migration (if not applied to the database) ordotnet ef database update <target_migration_name>
to roll back to a specific migration. - Multiple Databases: EF Core Migrations supports multiple databases within the same application.
For more in-depth information, please refer to the official EF Core Migrations documentation.