Entity Framework Core Migrations
Database migrations allow you to evolve your database schema over time as your application's model changes. Entity Framework Core (EF Core) provides a powerful migration system that helps you manage these changes in a structured and automated way.
What are Migrations?
Migrations are a feature of EF Core that enables a code-first approach to database development. You define your application's domain model using C# classes, and EF Core translates these models into database schema operations. Migrations capture the changes between model versions and generate the necessary SQL commands to update the database accordingly.
Key Concepts
- Migration: A single snapshot of your database schema. Each migration represents a set of changes applied to the database.
DbContext
: The class that represents a session with the database and allows you to query and save data. EF Core uses yourDbContext
to infer changes to the database schema.IMigrationsAssembly
: The component responsible for discovering and loading migrations.MigrationsSqlGenerator
: The component that generates SQL commands from migration operations.
Common Migration Commands
EF Core migrations are typically managed using the .NET CLI. Ensure you have the EF Core tools installed:
dotnet tool install --global dotnet-ef
1. Add a Migration
This command inspects your DbContext
and compares it to the existing migrations to generate a new migration file that represents the detected changes.
dotnet ef migrations add InitialCreate
Replace InitialCreate
with a descriptive name for your migration.
2. Apply Migrations
This command applies all pending migrations to the database, bringing it up to the latest schema version.
dotnet ef database update
You can also specify a target migration:
dotnet ef database update ApplySpecificMigration
3. Remove the Last Migration
If you need to undo the last applied migration, you can use this command. Note that this only reverts the code; you'll need to manually revert database changes or use --force
to drop the database.
dotnet ef migrations remove
4. Generate SQL Script
This command generates a SQL script that can be executed manually against your database. This is useful for deployments or for reviewing the changes.
dotnet ef migrations script
To script all migrations:
dotnet ef migrations script --from-migration InitialCreate --to-migration AnotherMigration
Customizing Migrations
EF Core migrations offer extensive customization options:
Customizing Generated Code
Each migration consists of two methods:
Up()
: Contains the operations to apply the migration.Down()
: Contains the operations to revert the migration.
You can manually edit these methods to fine-tune the generated SQL or add custom logic.
Down()
method correctly reverts the changes made in the Up()
method to avoid data loss or corruption.
Using Raw SQL
For complex operations not directly supported by EF Core's migration API, you can execute raw SQL commands.
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourApp.Migrations
{
[Migration("20231027100000_AddCustomData")]
partial class AddCustomData
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("INSERT INTO Logs (Message) VALUES ('Migration Applied')");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM Logs WHERE Message = 'Migration Applied'");
}
}
}
Best Practices
- Descriptive Migration Names: Use clear and concise names for your migrations (e.g.,
AddUserTable
,UpdateProductPriceColumn
). - Atomic Migrations: Aim for migrations that perform a single logical change.
- Review Generated Scripts: Always review the SQL generated by migrations before applying them to production environments.
- Version Control: Treat migration files as code and commit them to your version control system.
- Testing: Thoroughly test your migrations in development and staging environments before deploying to production.
dotnet ef database update
to apply it.
For more in-depth information and advanced scenarios, please refer to the official EF Core Migrations Documentation.