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

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.

Note: Always back up your database before applying any migrations, especially in production environments.

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

By mastering EF Core migrations, you can confidently manage your database schema alongside your application code, leading to more robust and maintainable applications.