TExcelTAD
Home › ASP.NET Core › DbContext & Migrations

DbContext & Migrations

In the previous lesson we created Blog, Post and AppDbContext. But the database file does not have any tables yet. Migrations are how EF Core creates and evolves the schema: each migration is a C# file describing the change from one version of your model to the next, and the tool applies them in order.

Configuring the model

EF Core builds a model of your entities from conventions. When conventions are not enough, override OnModelCreating and use the Fluent API (or data-annotation attributes on the entities):

csharp
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Blog> Blogs => Set<Blog>();
    public DbSet<Post> Posts => Set<Post>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>(b =>
        {
            b.Property(x => x.Title).HasMaxLength(100);
            b.HasIndex(x => x.Title).IsUnique();
        });

        modelBuilder.Entity<Post>(p =>
        {
            p.Property(x => x.Title).HasMaxLength(200);
            p.HasIndex(x => x.PublishedOn);
        });
    }
}
Convention Result
Property Id or BlogId on Blog Primary key
int/long key Value generated by the database
Non-nullable reference type (string) NOT NULL column
string? Nullable column
int BlogId + Blog Blog on Post Foreign key to Blogs
DbSet<Post> Posts Table named Posts

Installing the tool

dotnet ef is a .NET tool. Install it once per machine (or as a local tool in the repo):

bash · try it yourself
$ dotnet tool install --global dotnet-ef --version 9.0.10
$ dotnet ef --version
You can invoke the tool using the following command: dotnet-ef
Tool 'dotnet-ef' (version '9.0.10') was successfully installed.
Entity Framework Core .NET Command-line Tools
9.0.10

Creating the first migration

bash · try it yourself
$ dotnet ef migrations add InitialCreate
$ ls Migrations
Build started...
Build succeeded.
Done. To undo this action, use 'ef migrations remove'
20261016090000_InitialCreate.cs
20261016090000_InitialCreate.Designer.cs
AppDbContextModelSnapshot.cs

The migration file has an Up method (apply) and a Down method (revert). A shortened version:

csharp
public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Blogs",
            columns: table => new
            {
                Id = table.Column<int>(type: "INTEGER", nullable: false)
                    .Annotation("Sqlite:Autoincrement", true),
                Title = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false)
            },
            constraints: table => table.PrimaryKey("PK_Blogs", x => x.Id));

        // ... CreateTable("Posts") with FK_Posts_Blogs_BlogId, plus indexes
    }

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

The model snapshot (AppDbContextModelSnapshot.cs) records what the model looked like after the latest migration. Next time you run migrations add, EF Core compares your current model against the snapshot to work out what changed.

Applying migrations

bash · try it yourself
$ dotnet ef database update
Build started...
Build succeeded.
Applying migration '20261016090000_InitialCreate'.
Done.

EF Core also creates a __EFMigrationsHistory table that lists every migration already applied, so database update only runs the new ones.

Evolving the schema

Suppose posts need an optional subtitle. Add the property, then add a migration:

csharp
public string? Subtitle { get; set; }
bash · try it yourself
$ dotnet ef migrations add AddPostSubtitle
$ dotnet ef migrations list
$ dotnet ef database update --verbose | grep ALTER
Build started...
Build succeeded.
Done. To undo this action, use 'ef migrations remove'
Build started...
Build succeeded.
20261016090000_InitialCreate
20261016091500_AddPostSubtitle (Pending)
      ALTER TABLE "Posts" ADD "Subtitle" TEXT NULL;

The idea behind diffing

A migration is a diff between two models. This plain-C# program compares an old and a new model (table → columns) and prints the operations a migration would need:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var snapshot = new Dictionary<string, string[]>
{
    ["Blogs"] = new[] { "Id", "Title" },
    ["Posts"] = new[] { "Id", "Title", "Body", "PublishedOn", "BlogId" },
};

var current = new Dictionary<string, string[]>
{
    ["Blogs"] = new[] { "Id", "Title" },
    ["Posts"] = new[] { "Id", "Title", "Subtitle", "Body", "PublishedOn", "BlogId" },
    ["Tags"] = new[] { "Id", "Name" },
};

foreach (var table in current.Keys.Except(snapshot.Keys))
    Console.WriteLine(
quot;CreateTable {table} ({string.Join(", ", current[table])})"); foreach (var table in snapshot.Keys.Except(current.Keys)) Console.WriteLine(
quot;DropTable {table}"); foreach (var table in current.Keys.Intersect(snapshot.Keys)) { foreach (var col in current[table].Except(snapshot[table])) Console.WriteLine(
quot;AddColumn {table}.{col}"); foreach (var col in snapshot[table].Except(current[table])) Console.WriteLine(
quot;DropColumn {table}.{col}"); }
CreateTable Tags (Id, Name)
AddColumn Posts.Subtitle

Useful commands

Command What it does
dotnet ef migrations add <Name> Create a migration from model changes
dotnet ef migrations remove Delete the last migration (if not yet applied)
dotnet ef migrations list Show migrations and which are pending
dotnet ef database update Apply all pending migrations
dotnet ef database update <Name> Migrate up or down to a specific migration
dotnet ef migrations script --idempotent Generate a SQL script safe to run on any version
dotnet ef migrations bundle Build a self-contained executable that applies migrations

Tip: For production, prefer generating a SQL script or a migration bundle and running it as a deployment step. Calling db.Database.Migrate() at app startup is convenient for demos but risky when several instances start at once.

Seeding data

EF Core 9 adds UseSeeding/UseAsyncSeeding, which run after migrations are applied (and from EnsureCreated):

csharp
builder.Services.AddDbContext<AppDbContext>(options => options
    .UseSqlite("Data Source=blog.db")
    .UseSeeding((context, _) =>
    {
        if (!context.Set<Blog>().Any())
        {
            context.Set<Blog>().Add(new Blog { Title = "Welcome" });
            context.SaveChanges();
        }
    }));

Test yourself

What does EF Core compare against to decide what a new migration should contain?

  1. The live database schema
  2. The model snapshot file
  3. The previous git commit
  4. appsettings.json

Which table does EF Core use to remember which migrations have been applied?

  1. sqlite_master
  2. __Migrations
  3. dbo.Schema
  4. __EFMigrationsHistory

With nullable reference types enabled, how is a string? property mapped?

  1. As a nullable column
  2. As NOT NULL with an empty default
  3. It is ignored
  4. As a separate table