Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 41 ยท Migrations

Migrations: the Basics

Understand EF Core migrations - the model snapshot, dotnet ef migrations add, what the generated Up and Down methods contain, and how a migration history table tracks the schema.

Your C# model changes all the time: a new property, a renamed class, a new relationship. The database must change with it, and it must do so in a way you can repeat on your laptop, on a test server and in production. Migrations are EF Core's answer: small, versioned C# files that each describe one step from the old schema to the new one.

The dotnet ef tool and real databases cannot run on this site, so commands and generated code are read-only. The runnable stand-ins model the core idea: comparing a snapshot with the current model and producing steps.

The idea in one picture

flowchart LR
    A["C# model<br/>(entities + config)"] --> B["dotnet ef migrations add"]
    S["Model snapshot<br/>(last known model)"] --> B
    B --> C["Migration file<br/>Up and Down"]
    C --> D["dotnet ef database update"]
    D --> E["Database schema<br/>+ __EFMigrationsHistory"]

EF Core compares the model with the snapshot, writes the difference as a migration, and applies it to the database.

Three things matter:

  1. The model: your entities and configuration as they are now.
  2. The model snapshot: a generated file (ShopContextModelSnapshot.cs) that records the model as of the last migration. It is how EF Core knows what changed, without connecting to the database.
  3. The history table: __EFMigrationsHistory in the database lists which migrations were applied.

Installing the tool

TEXT
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

The Design package is needed in the project that holds your context (or the startup project). Run dotnet ef --version to check.

Creating the first migration

Suppose you have this model:

C#
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

Run:

TEXT
dotnet ef migrations add InitialCreate

EF Core creates a Migrations folder with three files:

  • 20260115093012_InitialCreate.cs: the migration (a timestamp prefix keeps the order).
  • 20260115093012_InitialCreate.Designer.cs: metadata, with the model as of this migration.
  • ShopContextModelSnapshot.cs: the current snapshot.

Reading a migration

C#
public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Products",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("Sqlite:Autoincrement", true),
                Name = table.Column<string>(nullable: false),
                Price = table.Column<decimal>(type: "TEXT", nullable: false)
            },
            constraints: table => table.PrimaryKey("PK_Products", x => x.Id));
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(name: "Products");
    }
}

Up moves the database forward and Down undoes it. They are ordinary C# code that you can read, review in a pull request and edit. Always read the generated migration, especially for renames and drops.

Evolving the model

Add a property:

C#
public string? Description { get; set; }

Then run dotnet ef migrations add AddProductDescription. The new migration only contains the difference:

C#
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<string>(name: "Description", table: "Products", nullable: true);
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(name: "Description", table: "Products");
}

The rename trap

If you rename Name to Title, EF Core sees a dropped column and a new column, and the data in Name would be lost. Fix the generated migration by hand:

C#
migrationBuilder.RenameColumn(name: "Name", table: "Products", newName: "Title");

Delete the DropColumn/AddColumn pair EF Core generated. Renames of tables and columns are the most common reason to edit a migration.

Useful commands

Command Purpose
dotnet ef migrations add Name Create a migration from the model difference
dotnet ef migrations remove Delete the last migration (only if not applied elsewhere)
dotnet ef migrations list List migrations and whether they are applied
dotnet ef database update Apply all pending migrations
dotnet ef database update Previous Roll the database back to an earlier migration
dotnet ef migrations script Produce SQL instead of touching the database

Never delete an applied migration file by hand; use remove (which also fixes the snapshot), and never edit a migration that others have already applied, add a new one instead.

Migration workflow

Change model Edit your entities
migrations add Generate Up and Down
Review Read the generated code
database update Apply to the database

Commit migrations to git

1 / 2

Stand-in: diff a snapshot and a model

This stand-in is not EF Core. It stores a snapshot as a set of table.column names, compares it with the current model and prints the Up steps, including how a rename shows up as drop plus add.

C# Stand-in: model versus snapshot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Stand-in: the history table decides what is pending

C# Stand-in: pending migrations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the model snapshot for?

    EF Core compares the current model with the snapshot, so it does not need to connect to the database to create a migration.
  2. 2. You rename a property and add a migration. What does EF Core generate by default?

    EF Core cannot tell a rename from a drop plus add. Replace the generated pair with RenameColumn by hand.
  3. 3. Which table records which migrations have been applied?

    __EFMigrationsHistory lists the migration ids that the database already has.
  4. 4. How do you undo the last migration that was never applied to any database?

    migrations remove deletes the files and rewinds the snapshot correctly.

Summary

  • A migration is a versioned C# class with Up and Down, generated from the difference between the model and the snapshot.
  • __EFMigrationsHistory tracks what a database has applied.
  • Always read generated migrations; fix renames by hand with RenameColumn.
  • Commit migrations to source control and never edit one that others have applied.

Next: Applying Migrations: Update, Scripts and Bundles