Skip to the workspace
Pebellslearn by building
Object Relational Mapping  ›  Lesson

Code First and Migrations — The Schema Follows Your Classes

Code First + Migrations 14 minIn code-first development the C# model is the source of truth, and each migration is a versioned, reversible step that brings the database schema in line with it.

aspnet core / Code First and Migrations — The Schema Follows Your Classes

Explore each scene at your own pace.

01 · The rule

The rule

Code First and Migrations — The Schema Follows Your Classes

ReadingRoom's Book class needs an ISBN. You could log into the database and add a column by hand — then do it again on the test server, and again in production, and hope nobody forgets. Code first reverses the direction: you change the C# class, and EF Core generates a versioned script that changes every database the same way.

The rule

Change the class, add a migration, update the database.

Migrations need the EF tools once per machine and the design package once per project:

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

Then the loop is always the same:

dotnet ef migrations add AddBookIsbn   # compare model to snapshot, write a migration
dotnet ef database update              # apply pending migrations to the database

A migration is a C# class with two methods:

public partial class AddBookIsbn : Migration
{
    protected override void Up(MigrationBuilder mb) =>
        mb.AddColumn<string>(name: "Isbn", table: "Books", nullable: true);

    protected override void Down(MigrationBuilder mb) =>
        mb.DropColumn(name: "Isbn", table: "Books");
}

Up moves the schema forward; Down undoes it. EF records every applied migration in a table called __EFMigrationsHistory, so each database knows exactly which steps it has had. A model snapshot file in the project remembers the last known model, which is how the next migrations add works out what changed.

Useful extras: dotnet ef migrations remove deletes the last migration if it has not been applied; dotnet ef migrations script produces plain SQL you can review and run in a deployment.

Rules like maximum lengths and relationships come from attributes ([MaxLength(20)]) or from OnModelCreating in the DbContext, and they flow into migrations too.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.