Detecting Missing Migrations in EF Core: A Guide for .NET Developers

Entity Framework Core has made database evolution straightforward with the Code-First approach. However, in real-world projects — especially when development moves fast or many people work on the same codebase — it’s easy to forget to generate a migration after changing your model.

This silent oversight can cause all sorts of headaches at runtime or deployment time.

In this article, I’ll show you how to detect missing migrations in EF Core, keep your model and database in sync, and prevent these tricky issues before they even happen.

What is a “Missing Migration”?

missing migration happens when you change your C# entity model but forget to create the corresponding migration using EF Core’s CLI or Package Manager Console.

This leads to problems like:

  • Your database doesn’t reflect recent model changes.
  • Running Update-Database applies nothing despite model updates.
  • A newly added migration suddenly includes a huge batch of unexpected changes.
  • Your production environment crashes because of schema mismatches.

How to Detect Missing Migrations in EF Core

Let’s explore a few practical ways to catch missing migrations, with examples you can try today.

1. Try Adding a Migration as a Quick Check

Run this command:

dotnet ef migrations add DetectChanges --no-build
  • If EF Core creates an empty migration, your model matches the last snapshot.
  • If the migration contains operations, it means you forgot to generate a migration earlier.

Remember to clean up afterwards:

dotnet ef migrations remove

2. Compare Your Current Model with the Migration Snapshot in Code

You can compare the current model with the last snapshot programmatically:

using var context = new AppDbContext();
var services = context.GetInfrastructure();
var modelDiffer = services.GetRequiredService<IMigrationsModelDiffer>();
var migrationsAssembly = services.GetRequiredService<IMigrationsAssembly>();
var currentModel = services.GetRequiredService<IModel>();
var snapshotModel = migrationsAssembly.ModelSnapshot?.Model;
var diffs = modelDiffer.GetDifferences(
snapshotModel?.GetRelationalModel(),
currentModel.GetRelationalModel());
if (diffs.Any())
{
Console.WriteLine("⚠️ Model changes not captured in a migration.");
}
else
{
Console.WriteLine("✅ Your model matches the last migration snapshot.");
}

⚠️ Note: These are internal EF Core services, so be cautious when upgrading EF Core versions.

3. Check for Pending Migrations at Runtime

This only tells you if there are unapplied migrations, not if migrations are missing:

var pending = context.Database.GetPendingMigrations();
if (pending.Any())
{
Console.WriteLine("⚠️ Pending migrations: " + string.Join(", ", pending));
}

4. Automate the Detection in CI/CD Pipelines

You can create a temporary migration and check if it generates any changes, then remove it:

$migrationName = "__AutoCheck"
dotnet ef migrations add $migrationName --no-build
$hasChanges = Select-String -Path ".\Migrations\$migrationName.cs" -Pattern "migrationBuilder\."if ($hasChanges) {
Write-Host "Uncommitted model changes detected."
dotnet ef migrations remove
exit 1
} else {
dotnet ef migrations remove
Write-Host "No missing migrations."
}

Integrate this into your pipeline to catch missing migrations early.

5. Manually Inspect the Snapshot File

Open Migrations/YourDbContextModelSnapshot.cs and verify it matches your current model. This is a good step during code reviews.

6. Prevent Startup if Migrations Are Missing

Fail fast in your application startup if there are unapplied migrations:

public static class MigrationValidator
{
public static void EnsureUpToDate(IServiceProvider services)
{
using var scope = services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var pending = context.Database.GetPendingMigrations();
if (pending.Any())
{
throw new InvalidOperationException("⚠️ Pending migrations: " + string.Join(", ", pending));
}
}
}

Call this in your Program.cs:

MigrationValidator.EnsureUpToDate(app.Services);

Handling Multiple DbContexts

If your project uses more than one DbContext, extend these checks by specifying the context explicitly:

dotnet ef migrations add AutoCheck --context OrdersDbContext --no-build

Example PowerShell loop:

$contexts = @("AppDbContext", "OrdersDbContext")
foreach ($ctx in $contexts) {
dotnet ef migrations add __Check__$ctx --context $ctx --no-build
# Inspect changes...
dotnet ef migrations remove --context $ctx --no-build
}

And runtime validation:

public static void EnsureAllDbContextsAreUpToDate(IServiceProvider services)
{
Validate<AppDbContext>(services);
Validate<OrdersDbContext>(services);
}

Quick Comparison of Methods

Method Detects Missing Migrations Detects Unapplied Migrations Best Use Case dotnet ef migrations add ✅ ❌ Local development Database.GetPendingMigrations() ❌ ✅ Runtime validation Programmatic snapshot diff ✅ ❌ Automated tests CI script with fake migration ✅ ❌ CI/CD pipelines Manual snapshot inspection ✅ ❌ Code reviews

Final Thoughts

Missing migrations are a subtle but costly problem — often discovered too late. By integrating these checks into your workflow and CI pipelines, you ensure your EF Core model, migrations, and database schema stay perfectly in sync, avoiding deployment surprises and runtime errors.



=========================================

You can follow the @adrianbailador

https://medium.com/@adrianbailador/detecting-missing-migrations-in-ef-core-a-guide-for-net-developers-5de35ac335e8

Comments

Popular posts from this blog

Tree view in winforms using c#

how to Replace null value with 0 Using C#

how to fetch all HTML Table Records and modify all records accordingly using jquery and Javascript