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

Managing Model Snapshots

Understand the role of the model snapshot file in detecting schema drift.

In this lesson, you will learn how Entity Framework Core uses the model snapshot file to identify when your C# model has diverged from your database schema.

What is the Model Snapshot?

When you work with EF Core Migrations, the DbContextModelSnapshot.cs file is automatically generated and updated inside your Migrations folder. You might be tempted to ignore it, but this file is the "source of truth" regarding the state of your database as it was after the last migration was applied.

Think of it as a historical record. When you run dotnet ef migrations add, EF Core doesn't actually look at your physical database to figure out what changed. Instead, it compares your current C# model (your DbContext and entity classes) against the configuration saved in the ModelSnapshot file.

Detecting Schema Drift

If you change an entity property—for example, renaming a column or changing a data type—EF Core compares the current state of your code to the snapshot. If the two don't match, EF Core calculates the "delta" (the difference) and generates a new migration file containing the necessary MigrationBuilder commands to sync the database.

Consider this scenario:

  1. You add a property public string PhoneNumber { get; set; } to an entity.
  2. You run a migration.
  3. EF Core updates the ModelSnapshot to include PhoneNumber.

If you were to manually alter the database table using SQL but forget to update your C# entity, the ModelSnapshot would not match your code. If you then tried to add another migration, EF Core might generate unnecessary or conflicting code because the snapshot is still expecting the old structure.

The snapshot prevents "schema drift" by ensuring that every migration is built upon the known, verified state of your model. By keeping this file consistent with your code, you ensure that your migrations remain predictable and avoid "ghost" changes that don't actually exist in your class definitions.

Key Takeaway: The model snapshot serves as the baseline for migration generation, allowing EF Core to calculate precisely what has changed since your last update without needing to query your actual database.