Migrations in EF Core are a feature that lets you incrementally update your database schema to match your entity model. They generate code files that describe the changes needed—such as creating tables, adding columns, or altering indexes—so you can apply those changes to a database in a controlled, versioned way.

What Are Migrations and Why Do They Matter?

In Entity Framework Core, your application's data model is defined by C# classes (entities) and a DbContext. As your application evolves, those classes change: you add a property, rename a table, or introduce a relationship. Without migrations, you would have to manually keep the database schema in sync with your code, which is error-prone and hard to automate across environments.

Migrations solve this by capturing each change as a snapshot. Each migration is a set of instructions—written in C#—that can be applied to a database to bring it from one version to the next. EF Core also records which migrations have been applied in a special table called __EFMigrationsHistory, so it knows what to run and what to skip.

This matters because it enables:

  • Version control for your schema – migrations live alongside your code in source control, so you can review, branch, and merge schema changes just like code.
  • Repeatable deployments – you can apply the same set of migrations to development, staging, and production databases, reducing the risk of drift.
  • Team collaboration – multiple developers can work on different features and generate migrations that are merged and applied in order.
  • Rollback capability – you can revert a migration to undo its changes, which is useful during development or when a deployment needs to be undone.

How Migrations Work Under the Hood

When you run a command like dotnet ef migrations add InitialCreate, EF Core compares your current model (as defined by your DbContext and entity classes) against the last migration's snapshot. It then generates three files in a Migrations folder:

  • A migration file (e.g., 20250315120000_InitialCreate.cs) containing Up and Down methods. The Up method applies the changes; the Down method reverts them.
  • A designer file (e.g., 20250315120000_InitialCreate.Designer.cs) that contains a snapshot of the model at the time the migration was created.
  • A model snapshot file (e.g., MyDbContextModelSnapshot.cs) that represents the current state of the model. This file is updated with each new migration and is used to calculate the next set of changes.

The migration file's Up method typically contains calls like migrationBuilder.CreateTable, migrationBuilder.AddColumn, or migrationBuilder.CreateIndex. These are translated into SQL statements when you apply the migration.

To apply migrations, you can use the command-line tool (dotnet ef database update) or call context.Database.Migrate() at application startup (though the latter is often discouraged in production due to concurrency and control concerns). The tool connects to the database, checks the __EFMigrationsHistory table, and runs any pending migrations in order.

Creating and Applying Migrations: Step by Step

Here is a typical workflow for using migrations in EF Core:

  1. Install the EF Core tools – Ensure you have the Microsoft.EntityFrameworkCore.Tools package (for Visual Studio) or the dotnet-ef global tool installed. For the .NET CLI, run dotnet tool install --global dotnet-ef.
  2. Define your model – Create your entity classes and a DbContext that exposes DbSet properties.
  3. Add your first migration – Run dotnet ef migrations add InitialCreate from the project directory. This creates the migration files based on your current model.
  4. Review the generated code – Open the migration file and check that the Up and Down methods reflect your intentions. You can modify them if needed (e.g., to add seed data or customize column types).
  5. Apply the migration – Run dotnet ef database update to apply the migration to the database specified in your connection string. Alternatively, generate a SQL script with dotnet ef migrations script and run it through your database deployment process.
  6. Repeat – As you change your model, add new migrations with dotnet ef migrations add <Name> and apply them with dotnet ef database update.

It's good practice to review each migration before applying it, especially in production. You can also generate an idempotent script (using --idempotent) that only applies migrations that haven't been applied yet, which is useful for automated deployments.

Common Problems and How to Fix Them

Migrations are powerful but can trip you up. Here are some frequent issues:

  • Pending model changes – If you change your model without adding a migration, EF Core will throw an error when you try to apply migrations or run the app (if using Migrate()). Always add a migration after model changes.
  • Merge conflicts in migration files – When multiple developers add migrations, the snapshot file can conflict. The fix is to remove the conflicting migrations, revert the model snapshot to the last committed version, and regenerate a single migration that includes all changes.
  • Applying migrations in production – Running Database.Migrate() at startup can cause race conditions if multiple instances start simultaneously. Instead, generate SQL scripts and apply them as part of your deployment pipeline, or use a dedicated migration tool.
  • Data loss warnings – Some operations (like dropping a column) can cause data loss. EF Core will warn you in the generated migration. Always review and, if necessary, write custom SQL to preserve data.
  • Customizing migrations – You can edit the generated migration code to add custom SQL, seed data, or adjust column types. Just be careful to keep the Down method consistent.

Migrations vs. EnsureCreated and Other Approaches

EF Core offers Database.EnsureCreated(), which creates the database schema if it doesn't exist, but it does not use migrations. EnsureCreated is convenient for rapid prototyping or testing, but it's not suitable for production because it bypasses the migration history and cannot be used to evolve the schema incrementally. Once you use EnsureCreated, you cannot switch to migrations without dropping and recreating the database.

Another approach is to use database-first development, where you generate entity classes from an existing database. In that case, migrations are typically not used; instead, you rely on the database schema as the source of truth. However, EF Core migrations are designed for code-first development, where your classes define the schema.

For teams that prefer SQL scripts, you can use migrations to generate SQL and then manage those scripts with a database project or a tool like Flyway or DbUp. This gives you more control over the deployment process.

Best Practices for Using Migrations

To get the most out of migrations, consider these practices:

  • Keep migrations small and focused – Each migration should represent a single logical change. This makes them easier to review and revert.
  • Commit migrations to source control – Treat migration files as part of your codebase. Never delete or modify a migration that has been applied to a shared database.
  • Use a separate project for migrations – In larger solutions, you can place migrations in a separate class library to keep your main project clean. Use the --project and --startup-project options with the CLI.
  • Test migrations – Apply migrations to a test database as part of your CI/CD pipeline to catch issues early.
  • Back up production data – Before applying migrations to production, ensure you have a recent backup. Some migrations can be destructive.
  • Use idempotent scripts for deployment – Generate scripts with --idempotent to safely apply migrations multiple times without errors.

Frequently Asked Questions

Can I use migrations with an existing database?

Yes, but it requires some setup. You can create an initial migration that matches the current schema and then mark it as applied using dotnet ef migrations add InitialCreate followed by dotnet ef database update with the --no-build option? Actually, the recommended approach is to create a migration and then insert a row into the __EFMigrationsHistory table manually to indicate it's already applied, or use the --ignore-changes option (available in EF Core 5+). This tells EF Core that the migration is already applied without actually running it.

How do I revert a migration?

To revert the last applied migration, run dotnet ef database update <PreviousMigrationName>. This will execute the Down method of the last migration and remove its record from the history table. To remove the migration files entirely, use dotnet ef migrations remove (after reverting the database).

What is the __EFMigrationsHistory table?

It's a table created by EF Core to track which migrations have been applied to the database. It contains columns like MigrationId and ProductVersion. You should not modify it manually unless you know what you're doing.

Can I customize the migration SQL?

Yes. You can edit the generated migration file to include custom SQL using migrationBuilder.Sql("..."). You can also generate a SQL script with dotnet ef migrations script and modify it before running it against the database.

Do migrations work with all database providers?

EF Core migrations are supported by most relational database providers, including SQL Server, PostgreSQL, MySQL, SQLite, and others. The generated SQL may vary slightly between providers, but the workflow is the same. Some NoSQL providers may have limited or no migration support.

How do I handle migrations in a team environment?

Coordinate migration creation to avoid conflicts. Establish a convention: for example, one developer creates a migration at a time, or use a branching strategy where migrations are added in feature branches and merged carefully. Always pull the latest changes before adding a new migration, and regenerate if conflicts occur.