Lesson 02 of 4 · 6 min read · Updated

EF Core 11 Migrations: Constraint-Free Relationships, Snapshot Conflicts and the dotnet-ef Config File

EF Core 11 adds several migration features: a relationship that exists in the model but not in the database, a snapshot that makes two diverging branches conflict in Git, a dotnet ef config file, and a wildcard for several DbContexts. This lesson builds one small model and tests each feature. The topic follows the NimblePros post "EF Core 11 Part I: Migrations Get Friendlier for Teams" by Barret Blake (link). The scenario and code here are our own, and some results differ from what you might expect, so read the notes marked as findings.

Technical Requirements

  1. .NET 11 SDK (we used RC 2) and EF Core 11 (we used 11.0.0-rc.3)
  2. SQLite, so no Docker is needed
  3. Sample code: github.com/Fcakiroglu16/dotnetacademy, branch efcore11-migrations-for-teams

The Model

A veterinary clinic has pets, vaccination records and visits. Vaccination records come from a lab feed and can arrive before the pet is registered, so that relationship should not be a database constraint. Visits are entered by the front desk after the pet exists, so they keep the normal foreign key. A second ScheduleDbContext holds on-call shifts.

src/Clinic.Data/ClinicDbContext.cs

using Microsoft.EntityFrameworkCore;

namespace Clinic.Data;

public class ClinicDbContext(DbContextOptions<ClinicDbContext> options) : DbContext(options)
{
public DbSet<Pet> Pets => Set<Pet>();
public DbSet<VaccinationRecord> Vaccinations => Set<VaccinationRecord>();
public DbSet<Visit> Visits => Set<Visit>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Still a relationship in the model (Include, tracking), but no FOREIGN KEY in the migration.
modelBuilder.Entity<VaccinationRecord>()
.HasOne(v => v.Pet)
.WithMany()
.HasForeignKey(v => v.PetId)
.ExcludeForeignKeyFromMigrations();

// Default behaviour: the database enforces this one.
modelBuilder.Entity<Visit>()
.HasOne(v => v.Pet)
.WithMany()
.HasForeignKey(v => v.PetId);
}
}

public class ScheduleDbContext(DbContextOptions<ScheduleDbContext> options) : DbContext(options)
{
public DbSet<OnCallShift> Shifts => Set<OnCallShift>();
}

Feature 1: A Relationship Without a Foreign Key

ExcludeForeignKeyFromMigrations() keeps the relationship in the EF model but leaves the constraint out of the migration. Here is the generated migration for both tables:

src/Clinic.Data/Migrations/20261106064048_InitialClinic.cs

migrationBuilder.CreateTable(
name: "Vaccinations",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
PetId = table.Column<int>(type: "INTEGER", nullable: false),
Vaccine = table.Column<string>(type: "TEXT", nullable: false),
GivenOn = table.Column<DateOnly>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Vaccinations", x => x.Id);
});

migrationBuilder.CreateTable(
name: "Visits",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
PetId = table.Column<int>(type: "INTEGER", nullable: false),
StartsAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Visits", x => x.Id);
table.ForeignKey(
name: "FK_Visits_Pets_PetId",
column: x => x.PetId,
principalTable: "Pets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});

migrationBuilder.CreateIndex(
name: "IX_Vaccinations_PetId",
table: "Vaccinations",
column: "PetId");

migrationBuilder.CreateIndex(
name: "IX_Visits_PetId",
table: "Visits",
column: "PetId");
}

Vaccinations has no ForeignKey call, but it still gets the IX_Vaccinations_PetId index. Visits has the constraint. The console app proves the difference:

1) vaccination record for a pet that is not registered yet (FK excluded):
saved; plain query finds 1 row
Include(Pet) finds 0 rows (required relationship = INNER JOIN)
2) visit for the same missing pet (FK kept):
rejected: SQLite Error 19: 'FOREIGN KEY constraint failed'.
3) the pet arrives late; the same record now resolves:
Pet navigation = Biscuit

Finding: the insert succeeds, but Include(v => v.Pet) returned zero rows. PetId is a non-nullable int, so the relationship is required and EF joins it with INNER JOIN. The orphan row is invisible to any query that includes the pet. If orphans must stay visible, make the key nullable (int? PetId) so EF uses a LEFT JOIN. Without the constraint, you also lose cascade deletes and orphan rejection, so integrity becomes your job.

Feature 2: One Config File for dotnet ef

Without it, every command needs --project src/Clinic.Data --startup-project src/Clinic.ConsoleApp --context ClinicDbContext. EF Core 11 reads .config/dotnet-ef.json, walking up from the current folder. Paths are relative to the folder that contains .config:

.config/dotnet-ef.json

{
"project": "src/Clinic.Data",
"startupProject": "src/Clinic.ConsoleApp",
"context": "ClinicDbContext"
}

Now the short commands work from the repo root:

dotnet ef migrations add InitialClinic
dotnet ef database update

Command-line options still override the file: --context ScheduleDbContext worked while the file named ClinicDbContext. The file sits next to dotnet-tools.json, so both can be committed and shared.

Feature 3: Diverged Migrations Conflict in Git

The model snapshot now stores the id of the latest migration. We created two branches from the same commit: one added MicrochipNumber to Pet, the other added Notes to Visit, each with its own migration. Merging them gave a conflict in ClinicDbContextModelSnapshot.cs:

<<<<<<< HEAD
public override string LastMigrationId => "20261106064424_AddMicrochipNumber";
=======
public override string LastMigrationId => "20261106064426_AddVisitNotes";
>>>>>>> feature-b

Without that line, nothing would tell you that two people extended the same snapshot. The fix we ran:

git merge --abort
dotnet ef migrations remove --force # --force reverts it in the database first if it was applied
git add -A && git commit -m "remove my migration"
git merge feature-b # clean merge now
dotnet ef migrations add AddMicrochipNumber

The result was a clean order: InitialClinic, AddVisitNotes, AddMicrochipNumber, and LastMigrationId points at the last one.

Feature 4: Create and Apply in One Step

dotnet ef database update <Name> --add scaffolds the migration, compiles it at runtime and applies it. We tested it on SQLite:

RunResult
First migration in an empty projectworked: "Migration ... was successfully created and applied"
Second migration after adding a propertyfailed

Finding: the second run scaffolded the whole schema again (CreateTable for every table) instead of one AddColumn, and the apply failed with SQLite Error 1: 'table "Pets" already exists'. We reproduced it on RC 2 and RC 3 in the two-project layout, and on RC 3 in a single project. It also updated the snapshot, so a plain migrations add afterwards produced an empty migration. If this happens, restore the snapshot and the migrations folder from Git, then use migrations add and database update as usual. Re-test on the final release before you rely on --add, and never point it at a shared database.

Feature 5: The Wildcard Context

--context "*" runs a command for every DbContext in the target project. Quote the asterisk so the shell does not expand it.

CommandResult on RC 3
dotnet ef database update --context "*"applied InitialClinic and InitialSchedule
dotnet ef migrations script --context "*"one script, 6 CREATE TABLE, one foreign key (Visits only)
dotnet ef migrations list --context "*"No DbContext named '*' was found.

The script confirms Feature 1: of the three relationships, only Visits ends up with a FOREIGN KEY. --idempotent is not supported for SQLite, so use another provider for that flag.

Summary

  1. ExcludeForeignKeyFromMigrations() removes the constraint but keeps the index and the model. Watch out for Include on a required relationship: orphans disappear.
  2. A .config/dotnet-ef.json removes repeated flags, and command-line options still win.
  3. The snapshot's LastMigrationId turns silent migration divergence into a merge conflict. Remove your migration, merge, then add it again.
  4. database update --add failed on the second migration in our RC tests. Verify it on the release build.
  5. --context "*" worked for database update and migrations script, but not for migrations list on RC 3.