C# / .NET Compendium PLEN
.NET / C# / Entity Framework Core

EF Core migrations in teamwork

The problem - migration conflicts when many people work

When several people on a team change the data model in parallel, each generates their own migration - the classic conflict scenario:

Developer A: adds a "Status" column to Order      → migration 20240115_AddOrderStatus
Developer B: adds a "DiscountCode" column to Order → migration 20240115_AddDiscountCode

Both migrations are based on the same "before the change" model - when both land on the main branch (e.g. via a merge), EF Core may get "lost" in the order, and the model snapshot (ModelSnapshot.cs) will conflict.

ModelSnapshot.cs - the source of conflicts in Git

EF Core stores a full snapshot of the current model in a generated file AppDbContextModelSnapshot.cs - this is the file that will have a merge conflict with parallel migrations, because both people modify the same generated file.

// AppDbContextModelSnapshot.cs (a fragment, GENERATED, don't edit by hand)
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
    protected override void BuildModel(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity("MyApp.Order", b =>
        {
            b.Property<int>("Id");
            b.Property<string>("Status"); // dodane przez Dewelopera A
            b.Property<string>("DiscountCode"); // dodane przez Dewelopera B - KONFLIKT MERGE
        });
    }
}

A practical way to resolve the conflict

Step 1: After a merge/rebase, if there is a conflict in ModelSnapshot.cs - do NOT try to merge that file by hand (it is generated, and manual editing is very error-prone).

Step 2: Locally remove the migrations that have not yet reached the production/shared database:

dotnet ef migrations remove  # removes the LAST migration (if not yet applied)

Step 3: Generate the migration anew, based on the already merged model (containing the changes of BOTH developers):

dotnet ef migrations add AddOrderStatusAndDiscountCode

Now EF Core generates one, consistent migration, based on a model containing both people's changes at once - ModelSnapshot.cs is recreated without a conflict, because it is a new, clean file after the merge.

A team rule - communicate before migrating

A practical recommendation many teams follow: before you generate a migration, pull (git pull) the latest changes from the main branch, so your migration is based on the freshest model, not an outdated version from this morning.

The order in which migrations are applied - __EFMigrationsHistory

EF Core tracks which migrations have already been applied to a given database in a special table:

SELECT * FROM __EFMigrationsHistory ORDER BY MigrationId;

If two migrations from different branches have colliding file names/timestamps, dotnet ef database update may try to apply them in an unexpected order - hence the rule "remove the unapplied migration and generate it anew after merging the code" is safer than trying to merge by hand.

"Empty" migrations (data seeding, operations not represented in the model)

Sometimes you need a migration that doesn't change the table structure, but e.g. fills in data:

dotnet ef migrations add SeedDefaultStatuses --  # pusta migracja
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.InsertData(
        table: "OrderStatuses",
        columns: new[] { "Id", "Name" },
        values: new object[] { 1, "Pending" });
}

Separating environments - dotnet ef database update in CI/CD

In team practice migrations are not applied by hand in production by a developer - a typical CI/CD pipeline:

# Fragment pipeline (pseudo-YAML)
steps:
  - run: dotnet ef database update --connection "$PROD_CONNECTION_STRING"
    # stosowane AUTOMATYCZNIE przy deploy, po code review i testach

This minimises the risk of "I forgot to update the production database" or of applying a migration in the wrong environment by accident.

Summary - a checklist for teamwork

  1. Always git pull the latest model before generating a new migration
  2. A conflict in ModelSnapshot.cs? Remove the unapplied local migration, generate it again after the merge
  3. Never edit generated migration/snapshot files by hand
  4. Migrations are applied automatically by CI/CD, not by hand in production
  5. For seeded data use dedicated, "empty" migrations with InsertData
Buy me a coffee