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

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:

You can manually edit these methods to fine-tune the generated SQL or add custom logic.

Tip: Always ensure the 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

Note: When working with multiple developers, it's crucial to coordinate migration generation to avoid conflicts. A common practice is to have one developer generate a migration and then have others run dotnet ef database update to apply it.
Important: Migrations should not be reordered or edited arbitrarily once they have been applied to a database. If you need to modify a past migration, it's often better to create a new migration that corrects or supplements the previous one.

For more in-depth information and advanced scenarios, please refer to the official EF Core Migrations Documentation.