Course contentsShow
← C#
Lesson 1122 of 1,90810. Entity Framework Core ModelingFree lesson

Database Migration Snapshots

Troubleshoot migration state issues by manually inspecting snapshot history.

In this lesson, you will learn how to troubleshoot migration state issues by manually inspecting your ModelSnapshot file to ensure your C# code and database schema remain perfectly synchronized.

The Role of the Model Snapshot

When you run dotnet ef migrations add, EF Core doesn't just create a migration file containing your changes; it also updates the *ModelSnapshot.cs file. This file acts as the "source of truth" for the current state of your entire database model. If your migration history gets messy—for example, if a team member manually edits a database column or a migration fails halfway—the snapshot can fall out of sync with your actual DbContext.

Inspecting the Snapshot

If you find that EF Core is trying to apply migrations that should have already been applied, or if it isn't detecting changes you’ve made to your entities, the first step is to open the file ending in ModelSnapshot.cs inside your Migrations folder.

This file contains the BuildModel method, which uses the Fluent API to describe every table, column, and relationship EF Core expects to see. Here is what a typical entry looks like:

modelBuilder.Entity("MyProject.Models.Product", b =>
{
    b.Property<int>("Id").ValueGeneratedOnAdd();
    b.Property<string>("Name").IsRequired();
    b.HasKey("Id");
    b.ToTable("Products");
});

When to Intervene

If you notice a discrepancy, such as a property appearing in your C# entity but missing from the BuildModel method, EF Core will attempt to "re-create" that schema element, causing migration errors.

Troubleshooting Checklist:

  1. Identify the Drift: Does the C# model (in your DbContext) match the BuildModel definition?
  2. Review Pending Migrations: Run dotnet ef migrations list. If the list doesn't match your actual database state, the snapshot may be stale.
  3. Manual Correction: In extreme cases where the snapshot is corrupted, you can manually update the BuildModel logic to match your database schema. However, treat this as a last resort; ideally, you should add a new migration to bridge the gap.

By treating the ModelSnapshot as a readable record of your database architecture, you can diagnose why migrations fail to detect or ignore specific model changes.

Key Takeaway: The ModelSnapshot is the definitive manifest of your database; when migrations behave unexpectedly, comparing your entities against the BuildModel method is the most reliable way to identify and fix drift.