In EF Core 10, what does dotnet ef migrations add generate, and what do a migration's Up and Down methods hold?
answer
- three files under Migrations/
- compares against a file, not the database
- ModelSnapshot and BuildTargetModel
- UTC timestamp prefix: yyyyMMddHHmmss
- MigrationBuilder operations, forward and inverse
basics
~20 sIt writes a timestamped migration class whose Up holds MigrationBuilder operations that apply the model change and whose Down holds the inverse, plus a Designer file and a rewritten model snapshot. Nothing reaches the database until migrations are applied.
solid answer
~40 s`dotnet ef migrations add AddCarCategory` builds the project, creates the `DbContext` the way the tools do at design time, and diffs its current model against the `ModelSnapshot` class left by the previous migration; it never connects to the database. It writes `<timestamp>_AddCarCategory.cs` with `Up` and `Down`, `<timestamp>_AddCarCategory.Designer.cs` carrying `[DbContext]`, `[Migration]` and `BuildTargetModel` (the model as of this migration), and it overwrites `RentalDbContextModelSnapshot.cs`. `Up` holds the `MigrationBuilder` calls that move the schema forward, such as `CreateTable`, `AddColumn` and `CreateIndex`; `Down` holds the inverse calls, scaffolded by diffing in the other direction. You review and edit that code before anything is applied, and you commit all three files together.
code
csharp · 24 linespublic partial class AddCarCategory : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CarCategories",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "character varying(40)", maxLength: 40, nullable: false)
},
constraints: table => table.PrimaryKey("PK_CarCategories", x => x.Id));
migrationBuilder.AddColumn<int>(
name: "CategoryId", table: "Cars", type: "integer", nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(name: "CategoryId", table: "Cars");
migrationBuilder.DropTable(name: "CarCategories");
}
}go deeper
Recall the three files the command writes, that Up applies and Down reverts, and that nothing touches the database until the migration is applied.
Explain that the diff runs against the ModelSnapshot class rather than the database, what BuildTargetModel freezes, and why an empty migration is a useful vessel for custom SQL.
Show the review habit: read the scaffolded operations for destructive steps, keep Down honest, and treat a stale or uncommitted snapshot as a defect that corrupts the next migration.
Weigh the snapshot-diff workflow against hand-written SQL migrations for a team, and set the review and naming rules that keep a long migration history trustworthy.
## What the command compares A **migration** in EF Core is a C# class that describes one step of schema change. `dotnet ef migrations add <Name>` creates the next step. It does not look at the database at all: it compares two **models** (EF Core's in-memory description of entity types, tables, columns, keys and indexes). 1. The tools build the target and startup projects. 2. They create your `DbContext` at design time (through an `IDesignTimeDbContextFactory<TContext>`, the app's service provider, or a parameterless constructor) and read its current model. 3. They load the **model snapshot**, a class deriving from `ModelSnapshot` that the previous migration left in the migrations assembly. 4. The migrations model differ computes the operations that turn the snapshot's model into the current one, and separately the operations that turn it back. 5. The scaffolder writes C# for both lists and rewrites the snapshot so it matches the current model. If any forward operation is flagged destructive (dropping a column or a table, changing a column's type, or making a nullable column required, among others), the command prints *An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.* ## The three files For a car-rental API whose context is `RentalDbContext`, `dotnet ef migrations add AddCarCategory` writes into `Migrations/` (or the folder given with `--output-dir`, and the namespace given with `--namespace`): | File | What it holds | Written when | |---|---|---| | `20261007093015_AddCarCategory.cs` | The partial class deriving from `Migration`, with `Up` and `Down` | Created once, by this command | | `20261007093015_AddCarCategory.Designer.cs` | `[DbContext(typeof(RentalDbContext))]`, `[Migration("20261007093015_AddCarCategory")]` and `BuildTargetModel`, the full model as it stood after this migration | Created once and then frozen | | `RentalDbContextModelSnapshot.cs` | `[DbContext]` and `BuildModel`, the model as of the latest migration | Rewritten by every `add` and `remove` (deleted when the only migration is removed) | The id prefix is a UTC timestamp in `yyyyMMddHHmmss` form, so migrations sort in the order they were created. The `[Migration]` id is what ends up in the `__EFMigrationsHistory` table once a database applies the migration. ## Up and Down - **`Up(MigrationBuilder migrationBuilder)`** lists the forward operations: `CreateTable`, `AddColumn`, `AlterColumn`, `CreateIndex`, `AddForeignKey`, `InsertData` for model-managed rows, and so on. Each call only records an operation; the provider's SQL generator turns them into SQL when the migration is applied or scripted. - **`Down(MigrationBuilder migrationBuilder)`** lists the operations that undo `Up`, in reverse order: `DropColumn` for an `AddColumn`, `DropTable` for a `CreateTable`. The scaffolder produces it by diffing the current model back to the snapshot. - `Up` is abstract on `Migration`. The base `Down` throws `NotSupportedException` ("The 'Down' method for this migration has not been implemented"), so deleting the scaffolded `Down` makes the migration impossible to revert. - `Down` is not free of risk: reverting an `AddColumn` drops that column and whatever data was written to it since. ## What the command does not do - It does not apply anything. The database is unchanged until the migration is applied. - It does not read `__EFMigrationsHistory`. `dotnet ef migrations list` is the command that connects and marks unapplied migrations with `(Pending)`. - It does not refuse when nothing changed. With no model change it scaffolds an **empty** migration, which is how you add a migration that only holds `migrationBuilder.Sql(...)` for a view, a trigger or a function. - It refuses a name an existing migration already uses: *The name 'AddCarCategory' is used by an existing migration.* ## Reviewing before you commit - Read every generated `Up` and `Down`: the differ is good, but a renamed property combined with another change can come out as a drop and an add. - Commit the migration, its Designer file and the snapshot together. The next developer's `migrations add` diffs against that snapshot, so a missing or stale snapshot makes their migration repeat or miss operations. - Keep the migration name meaningful, like a commit message: `AddCarCategory` says what the step does. ## Mistakes interviewers probe - **Editing the Designer file or the snapshot by hand.** Both are tool-owned. A hand edit makes the next diff lie, and the next `migrations remove` overwrites the snapshot from the Designer anyway. - **Scaffolding against the wrong startup project.** The tools create the context the way the startup project configures it; if that project points at another provider, the migration is written with that provider's store types and annotations. - **Treating `migrations add` as a sync with the database.** If someone changed the database by hand, the snapshot does not know, and the scaffolded migration may try to create what already exists. - **Moving files carelessly.** You may move migration files and change their namespace; new migrations are created as siblings of the last one, so keep them together.
- What happens if you run dotnet ef migrations add when the model has not changed?EF Core still scaffolds a migration, with empty `Up` and `Down` bodies, and rewrites the snapshot unchanged. That empty migration is the intended home for hand-written operations such as `migrationBuilder.Sql` creating a view, trigger or function EF Core does not model, with the matching drop in `Down`.
- Why does every migration keep its own Designer file with BuildTargetModel?It freezes the model as it stood right after that migration. `dotnet ef migrations remove` rebuilds the snapshot from the previous migration's `BuildTargetModel`, and the `[Migration]` attribute on the same file supplies the id that orders migrations and is written to `__EFMigrationsHistory`. Editing or losing it breaks those steps.
The snapshot is the floor plan pinned to the last page of a building's renovation logbook. To write the next entry you compare today's plan with that page; nobody walks through the building to measure it.
- dotnet ef migrations add reads the live database schema to find what changed.
- Adding a migration also applies it to the local database.
- The model snapshot can be deleted once migrations exist; EF rebuilds it.
- Down is computed at revert time from the Up method, so it can be deleted.
- Only the main migration file needs committing; the Designer file is build output.