LESSON 5 OF 19

Migrations Do Not Apply: Model Changes, the Wrong Startup Project and Migration Conflicts

Systematically troubleshoot EF Core 10 migration problems involving model changes, project and startup project selection, DbContext configuration and team migration conflicts.

30 dk 118

Introduction

In the previous lessons, we examined problems caused by the DbContext lifetime, entity tracking and incorrect use of AsNoTracking. This lesson focuses on migrations, which keep the database schema synchronized with the application model.

A migration may exist in the codebase and still fail to appear in the database. In other cases, a model was changed without creating a migration. The command may also succeed while using the wrong startup project or an unexpected connection string. In a team, two developers may create migrations from the same model snapshot, causing the migration tree to diverge.

Adding another migration is not always the correct first step. You should first determine which project EF Core is building, which DbContext it is creating and which database it is targeting.

How the migration process works

EF Core compares the current application model with the model snapshot stored by the latest migration. When it detects a difference, it generates migration operations in Up and Down methods and creates an updated snapshot.

It is important to distinguish three situations:

  • The model changed but no migration was created: The application model differs from the snapshot.
  • A migration was created but not applied: The migration exists in source code but is not recorded in __EFMigrationsHistory.
  • The migration was applied to another database: The command succeeded, but the developer is inspecting a different database.

A useful first diagnostic step is to list migrations while specifying the target project and startup project explicitly:

dotnet ef migrations list \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext

--project identifies the target project where migration files are generated. --startup-project identifies the application project executed by the tools. These options are especially important when the DbContext is in a class library and the web application is in a separate project.

Sample project structure

Assume the following solution structure:

Store.sln
├── Store.Domain
├── Store.Data
│   ├── StoreDbContext.cs
│   └── Migrations
└── Store.Api
    ├── Program.cs
    └── appsettings.json

StoreDbContext is defined in the data project. Store.Api is the startup project and provides application configuration, service registration and the connection string.

public sealed class StoreDbContext : DbContext
{
    public StoreDbContext(DbContextOptions<StoreDbContext> options)
        : base(options)
    {
    }

    public DbSet<Product> Products => Set<Product>();
}

The API project may register the context as follows:

builder.Services.AddDbContext<StoreDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("StoreDb")));

Problem 1: The model changed but no migration was created

Suppose we add a Sku property to the Product entity:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Sku { get; set; } = string.Empty;
}

If the developer runs dotnet ef database update immediately, EF Core may have no new migration to apply. EF Core does not automatically turn every C# model change into a production schema change. The change must first be represented by a migration.

The correct workflow is:

dotnet ef migrations add AddProductSku \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext

dotnet ef database update \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext

Always inspect generated migration files. Verify that the new column is added to the expected table, that no unintended destructive operation was generated and that default values are appropriate for existing rows.

Checking for pending model changes in code

EF Core 10 also provides an API that can detect whether the model differs from the latest migration snapshot. This can be useful in CI validation:

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<StoreDbContext>();
var migrator = db.Database.GetService<IMigrator>();

if (migrator.HasPendingModelChanges())
{
    throw new InvalidOperationException(
        "The model changed but no new migration was created.");
}

This check detects a difference between the current model and the latest migration snapshot. It does not determine whether an existing migration has been applied to the database. These are separate checks.

Problem 2: The wrong startup project is being used

The following command looks reasonable:

dotnet ef migrations add AddProductSku

However, when it is executed from a solution directory, the default project may not be the intended one. If Store.Data contains only the context and entity types, the tools may also need Store.Api to create the design-time context and resolve configuration.

A more reliable command explicitly identifies the project, startup project and context:

dotnet ef migrations add AddProductSku \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext

The equivalent Package Manager Console command is:

Add-Migration AddProductSku `
  -Project Store.Data `
  -StartupProject Store.Api `
  -Context StoreDbContext

Several symptoms can indicate an incorrect startup project:

  • EF Core cannot locate the expected DbContext.
  • The migration is generated in an unexpected project or directory.
  • A test or production connection string is used instead of the development one.
  • A design-time error such as “Unable to create an object of type DbContext” appears.

Using IDesignTimeDbContextFactory

When a solution contains multiple startup projects, worker services or custom hosting logic, a design-time factory can provide a more predictable context creation path:

public sealed class StoreDbContextFactory
    : IDesignTimeDbContextFactory<StoreDbContext>
{
    public StoreDbContext CreateDbContext(string[] args)
    {
        var options = new DbContextOptionsBuilder<StoreDbContext>();
        options.UseSqlServer(
            "Server=(localdb)\\MSSQLLocalDB;Database=StoreDev;Trusted_Connection=True;TrustServerCertificate=True");

        return new StoreDbContext(options.Options);
    }
}

Do not hard-code a production connection string in the factory. Its purpose is to provide reliable design-time construction, not to expose credentials in source control.

Problem 3: The migration exists but is not applied

Start by listing the migrations:

dotnet ef migrations list \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext

Then update the intended database explicitly:

dotnet ef database update \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext \
  --connection "Server=(localdb)\\MSSQLLocalDB;Database=StoreDev;Trusted_Connection=True;TrustServerCertificate=True"

An incorrect connection string is one of the most frequently missed causes. The application may load appsettings.Development.json, while the EF command may run under another environment. Check the server, database name and environment in diagnostic logs. Never write production credentials to logs or commit them to source control.

The __EFMigrationsHistory table records migrations applied to a particular database. If the migration exists in the project but is absent from this table, it has not been applied to that database.

Problem 4: Parallel migrations and merge conflicts

Imagine that two developers branch from the same initial migration. Developer A creates AddProductSku, while developer B creates AddProductPrice. Both migrations are generated from the same older snapshot.

It is not safe to solve this situation by merely sorting or renaming migration files. Migrations are not only SQL operations; they also contain a model snapshot and designer metadata. One migration may contain a snapshot that does not include the other branch's change.

The recommended resolution workflow is:

  1. Abort the merge or return the branch to a coherent pre-merge state.
  2. Remove your migration files from source control while keeping the model changes.
  3. Merge the other developer's migration and current snapshot.
  4. Re-create your migration on top of the merged model.
  5. Apply the result to a test database and inspect the generated SQL.

If the parallel migrations have already been applied to a shared database, do not simply delete their source files. Create a corrective migration or follow a controlled rollback plan. Removing migration code that is already recorded in a shared database can make future deployments harder to reason about.

Applying migrations in production

Running dotnet ef database update is convenient for local development. In production, migration deployment should generally be a reviewable and repeatable deployment step.

Generate a SQL script with:

dotnet ef migrations script \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext \
  --output artifacts/store-migrations.sql

The script can be reviewed by the team, approved by a database administrator and executed by the deployment pipeline. A migration bundle can also apply migrations without requiring the complete source tree on the production server:

dotnet ef migrations bundle \
  --project Store.Data \
  --startup-project Store.Api \
  --context StoreDbContext \
  --output artifacts/efbundle

Automatically running migrations at every application startup may be acceptable in small development environments. In production systems with multiple instances, restricted permissions, long-running data transformations or strict deployment controls, it should be evaluated carefully.

Common mistakes

  • Changing only the entity class: The database schema does not change without a migration.
  • Running the command in the wrong project: Leaving --project and --startup-project implicit can produce unexpected results.
  • Inspecting the wrong database: The environment or connection string may be different.
  • Renaming migration files manually: This does not reliably repair migration ordering or metadata.
  • Deleting an applied migration: Prefer a corrective migration for migrations recorded in a shared database.
  • Applying migrations during application startup in production: This can bypass deployment review and permission policies.

Short practice exercise

Add an IsActive property to the Product entity. Then complete the following steps:

  1. Save the model change.
  2. Create a migration with Store.Data as the target project and Store.Api as the startup project.
  3. Inspect the generated column operation for the Products table.
  4. List the migrations.
  5. Apply the migration only to the development database.
  6. On a second branch, add another property and observe how a migration conflict can occur.

Diagnostic question: If the latest migration appears in the list but the column is missing from the database, what three things should you check? The expected answers are the startup project, the connection string and the __EFMigrationsHistory record.

Conclusion

The key to solving migration problems is not memorizing commands. It is making the model, context, project, startup project and database used by the EF Core tools explicit and observable. A model change must be represented by a migration, the migration must be applied with the correct configuration and the model snapshot must remain consistent across team branches.

Direct database updates are useful during local development. For production, reviewable SQL scripts or migration bundles provide a more controlled deployment process. In the next lesson, we will examine relational schema problems and Foreign Key errors created by migrations in more detail.

Sources