Migrations and seeding
Migrations are version control for your database schema: every model change becomes a reviewed file with Up and Down, applied in order and recorded in a history table. This note also covers rollback, SQL scripts for production, scaffolding an existing database and seeding.
53.1 The problem: EnsureCreated
- EnsureCreated creates the database and tables on the first run, and everything works.
- Add a Stock property to Product and GET /products returns 500: no such column p.Stock.
- EnsureCreated only checks whether tables exist; it has no idea which version the database is on.
Output
# Stock added to Product, app run again$ curl -i localhost:5053/productsHTTP/1.1 500 Internal Server Errorfail: ...Database.Command[20102] SELECT "p"."Id", "p"."Name", "p"."Price", "p"."Stock" FROM "Products" AS "p"!SqliteException: SQLite Error 1:!'no such column: p.Stock'.- Step 1
1.EnsureCreated: only checks tables
- Step 2
2.Tables found: no change made
- Step 3
3.No version: Stock column missing
We need version control for the schema = migrations
53.2 Setup: dotnet-ef as a local tool
- Install dotnet-ef as a local tool (not global); the version is written to dotnet-tools.json.
- Add the Microsoft.EntityFrameworkCore.Design package, which the tool needs.
- Commit the manifest; a teammate runs dotnet tool restore and gets the same version.
Terminal
# once per projectdotnet new tool-manifestdotnet tool install dotnet-efdotnet add package \ Microsoft.EntityFrameworkCore.Design # a teammate after git clonedotnet tool restoreOutput
$ dotnet tool restoreTool 'dotnet-ef' (version '10.0.14') was restored.Restore was successful.$ dotnet ef --versionEntity Framework Core .NET Command-line Tools10.0.1453.3 First migration and database update
- Remove EnsureCreated and start fresh with Product (Id, Name, Price).
- migrations add InitialCreate reads the model and creates 3 files: the migration (Up/Down), its Designer file and the model snapshot.
- migrations list shows it as Pending until it is applied.
- database update creates __EFMigrationsHistory, runs the migration and records its name: that table is the database's version.
Terminal
dotnet ef migrations add InitialCreatedotnet ef migrations listdotnet ef database updateOutput
$ ls Migrations20261106202744_InitialCreate.cs20261106202744_InitialCreate.Designer.csShopDbModelSnapshot.cs$ dotnet ef migrations list20261106202744_InitialCreate (Pending)$ dotnet ef database update CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" ( "MigrationId" TEXT NOT NULL ..., "ProductVersion" TEXT NOT NULL);Applying migration '20261106202744_InitialCreate'. CREATE TABLE "Products" (...); INSERT INTO "__EFMigrationsHistory" VALUES ('20261106202744_InitialCreate', '10.0.14');Done.53.4 A model change: AddStock
- Add Stock to Product, then migrations add AddStock.
- Up adds the column (AddColumn); Down removes the same column (DropColumn).
- database update runs ALTER TABLE and the endpoint now returns 200 OK.
C#
protected override void Up( MigrationBuilder migrationBuilder){ migrationBuilder.AddColumn<int>( name: "Stock", table: "Products", type: "INTEGER", nullable: false, defaultValue: 0);} protected override void Down( MigrationBuilder migrationBuilder){ migrationBuilder.DropColumn( name: "Stock", table: "Products");}Output
$ dotnet ef migrations add AddStockDone. To undo this action, use 'ef migrations remove'$ dotnet ef database updateApplying migration '20261106203211_AddStock'. ALTER TABLE "Products" ADD "Stock" INTEGER NOT NULL DEFAULT 0;Done.$ curl -i localhost:5053/productsHTTP/1.1 200 OK[]- Step 1
1.Change the model (Stock property)
- Step 2
2.dotnet ef migrations add -> Up + Down file
- Step 3
3.Review the file (catch data loss here)
- Step 4
4.dotnet ef database update -> entry in history
Migration files live in Git, the version lives in the database
53.5 Rollback: target an older migration
- database update InitialCreate runs AddStock's Down and deletes its history row.
- SQLite cannot drop a column in place, so EF copies the table without Stock (ef_temp_Products) and renames it.
- AddStock is Pending again; a plain database update applies it back.
Terminal
# rollback: target an older migrationdotnet ef database update InitialCreatedotnet ef migrations list # forward againdotnet ef database updateOutput
$ dotnet ef database update InitialCreateReverting migration '20261106203211_AddStock'. CREATE TABLE "ef_temp_Products" (Id, Name, Price); INSERT INTO "ef_temp_Products" ("Id", "Name", "Price") SELECT "Id", "Name", "Price" FROM "Products"; DROP TABLE "Products"; ALTER TABLE "ef_temp_Products" RENAME TO "Products"; DELETE FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20261106203211_AddStock';Done.$ dotnet ef migrations list20261106202744_InitialCreate20261106203211_AddStock (Pending)53.6 Production: migration SQL script
- Running dotnet ef against production from your laptop is risky; generate SQL that can be reviewed instead.
- The script wraps ALTER TABLE and the history insert in one transaction.
- -o writes it to a file (deploy.sql). --idempotent works on SQL Server / PostgreSQL, not on SQLite.
Terminal
# SQL for one step (from, to)dotnet ef migrations script \ InitialCreate AddStock # from AddStock to the latest, into a filedotnet ef migrations script AddStock \ -o deploy.sql # SQL Server / PostgreSQL onlydotnet ef migrations script --idempotentOutput
$ dotnet ef migrations script InitialCreate AddStockBEGIN TRANSACTION;ALTER TABLE "Products" ADD "Stock" INTEGER NOT NULL DEFAULT 0;INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")VALUES ('20261106203211_AddStock', '10.0.14');COMMIT;$ dotnet ef migrations script --idempotent!Generating idempotent scripts for migrations!is not currently supported for SQLite.53.7 Database First: scaffold
- For an existing database (e.g. an old billing system), dbcontext scaffold reads the tables and generates entities and a context.
- The snake_case column became FullName; the foreign key gave an Invoices navigation.
- Classes are partial: put your own code in a separate file, because scaffolding again overwrites generated files.
Terminal
dotnet ef dbcontext scaffold \ "Data Source=legacy.db" \ Microsoft.EntityFrameworkCore.Sqlite \ -o Legacy -c LegacyDb --no-onconfiguringC#
namespace Shop.Legacy; public partial class Customer{ public int CustomerId { get; set; } public string FullName { get; set; } = null!; public string? City { get; set; } public virtual ICollection<Invoice> Invoices { get; set; } = new List<Invoice>();}53.8 Seeding: HasData vs UseSeeding
- HasData makes the data part of the model: for fixed reference data like categories. Every row needs a fixed Id.
- The migration gets InsertData and database update inserts the rows.
- Demo data (sample products) should not be in the model: use UseSeeding / UseAsyncSeeding (EF Core 9+).
- The seed method checks AnyAsync first so data is never inserted twice; register both sync and async versions.
C#
protected override void OnModelCreating( ModelBuilder modelBuilder){ modelBuilder.Entity<Category>().HasData( new Category { Id = 1, Name = "Kitchen" }, new Category { Id = 2, Name = "Electronics" }, new Category { Id = 3, Name = "Books" });}C#
public static async Task SeedAsync( DbContext context, bool _, CancellationToken ct){ var db = (ShopDb)context; if (await db.Products.AnyAsync(ct)) return; db.Products.AddRange( new() { Name = "Kettle", Price = 1299 }, new() { Name = "Bottle", Price = 399 }); await db.SaveChangesAsync(ct);} // Program.csbuilder.Services.AddDbContext<ShopDb>(options => options.UseSqlite("Data Source=shop.db") .UseSeeding(DemoData.Seed) .UseAsyncSeeding(DemoData.SeedAsync));Output
$ dotnet ef database update # fresh shop.dbApplying migration '20261106202744_InitialCreate'.Applying migration '20261106203211_AddStock'.Applying migration '20261106203717_AddCategories'. SELECT EXISTS (SELECT 1 FROM "Products" AS "p") INSERT INTO "Products" ("Name", "Price", "Stock") INSERT INTO "Products" ("Name", "Price", "Stock")Done.$ dotnet ef database update # againNo migrations were applied. The database isalready up to date. SELECT EXISTS (SELECT 1 FROM "Products" AS "p")Done.| Point | HasData | UseSeeding / UseAsyncSeeding |
|---|---|---|
| Data type | Fixed reference data (categories) | Demo / sample data |
| Part of the model? | Yes, goes into migrations (InsertData) | No, runs after migrations |
| Ids | Must be fixed | Generated by the database |
| Duplicate guard | EF tracks rows by Id | Your own check (AnyAsync) |
53.9 Common mistakes
- migrations remove on an applied migration fails: revert it first, or if it ran on other databases add a new migration that undoes it.
- Dynamic values in HasData (DateTime.UtcNow) change the model on every build: PendingModelChangesWarning. Use a fixed date.
- Treating rollback as a safe undo: Down drops the Stock column, so that data is gone for good. Take a backup first.
Output
$ dotnet ef migrations remove!The migration '20261106203717_AddCategories' has!already been applied to the database. Revert it!and try again. If the migration has been applied!to other databases, consider reverting its!changes using a new migration instead.C#
// Wrong: model changes each time it is builtmodelBuilder.Entity<Category>().HasData( new Category { Id = 1, Name = "Kitchen", CreatedAt = DateTime.UtcNow }); // Right: fixed value, stable modelmodelBuilder.Entity<Category>().HasData( new Category { Id = 1, Name = "Kitchen", CreatedAt = new DateTime(2026, 1, 1) });53.10 Rules for migrations
- Keep dotnet-ef as a local tool and commit the manifest.
- Review every migration file before committing it.
- Never edit or remove a shared migration: create a new one instead.
- Production: run a reviewed SQL script or a migration bundle.
- HasData for fixed data, UseSeeding for demo data.
53.11 Interview tips
- Model change -> migrations add -> review Up and Down -> database update in development.
- __EFMigrationsHistory records which migrations ran; that is how EF knows the database version.
- Production: a reviewed SQL script (idempotent where supported) or a bundle; rollback = database update <TargetMigration>.
- EnsureCreated never updates an existing schema; it is only for demos and tests.