In EF Core 10, when do you seed a car-rental database's reference data with HasData, and when with UseSeeding?
answer
- model-managed data vs initialization code
- explicit non-zero keys for HasData
- InsertData, UpdateData, DeleteData
- Action<DbContext, bool> runs every time
- tools call the synchronous delegate
basics
~20 sHasData suits fixed rows with explicit keys, such as car categories; migrations add turns its changes into InsertData, UpdateData and DeleteData. UseSeeding, new in EF Core 9, runs after every EnsureCreated or migrate and must check for existing data.
solid answer
~40 s`HasData` in `OnModelCreating` makes rows part of the model: you supply the key, the rows are captured in the snapshot, and `migrations add` scaffolds `InsertData`, `UpdateData` or `DeleteData` when they change. It fits small, deterministic reference data like car categories, but it cannot rely on database-generated keys, and a changed key deletes and re-inserts the row. `UseSeeding` and `UseAsyncSeeding`, added in EF Core 9 on `DbContextOptionsBuilder`, take a delegate that runs after `EnsureCreated`, `Migrate`, `dotnet ef database update` or a bundle, every time, even when nothing was applied, so it must check what already exists. Use it for rows that need generated keys, external calls such as creating Identity users, or values depending on database state. The tools and bundles call the synchronous delegate, so configure `UseSeeding` even in an async app.
code
csharp · 18 linesbuilder.Services.AddDbContext<RentalDbContext>(options => options
.UseNpgsql(builder.Configuration.GetConnectionString("Rental"))
.UseSeeding((context, _) =>
{
if (!context.Set<Branch>().Any(b => b.Code == "HQ"))
{
context.Set<Branch>().Add(new Branch { Code = "HQ", City = "Lisbon" });
context.SaveChanges();
}
})
.UseAsyncSeeding(async (context, _, ct) =>
{
if (!await context.Set<Branch>().AnyAsync(b => b.Code == "HQ", ct))
{
context.Set<Branch>().Add(new Branch { Code = "HQ", City = "Lisbon" });
await context.SaveChangesAsync(ct);
}
}));go deeper
Know the two options: HasData rows with fixed keys that migrations insert, and UseSeeding code that runs when the database is created or migrated.
Explain why HasData needs explicit keys and a new migration for every change, why UseSeeding must check for existing rows, and why both seeding delegates are configured.
Choose per data set, keep non-deterministic values out of the model, and make sure the deployment path actually runs the seeding you rely on, since scripts never do.
Decide which data is part of the schema contract and versioned with migrations, and which is environment setup owned by deployment, across every environment the product runs in.
## Two mechanisms with different owners EF Core offers two built-in ways to put rows into a database alongside its schema. They look similar in a demo and behave very differently in production. - **`HasData`**, which the EF Core docs now call *model-managed data*, makes rows part of the **model**. Migrations own them. - **`UseSeeding` / `UseAsyncSeeding`**, added in EF Core 9, register **code** that runs whenever EF Core initializes or migrates the database. You own the logic. ## HasData: rows that live in the model ```csharp modelBuilder.Entity<CarCategory>().HasData( new CarCategory { Id = 1, Code = "ECON", Name = "Economy" }, new CarCategory { Id = 2, Code = "SUV", Name = "SUV" }, new CarCategory { Id = 3, Code = "VAN", Name = "Van" }); ``` - **Keys are mandatory.** Migrations are scaffolded without a database connection, so EF Core tracks each row by the key you give it. Leaving an `int` key at `0` fails with a message that a non-zero value is required, suggesting negative values to avoid collisions with normal rows. - **Foreign keys, not navigations.** A seeded row that points at another one sets the foreign key property, such as `CategoryId = 2`. - **Changes become operations.** When you add, edit or remove a `HasData` row and run `dotnet ef migrations add`, the migration contains `InsertData`, `UpdateData` or `DeleteData`. - **Nothing happens without a migration.** `Migrate` applies migrations; it does not inspect `HasData` on its own. Edit the data and forget the migration, and the database keeps the old rows. - **Changing a key is a delete plus an insert**, and rows edited outside migrations can be overwritten or cause errors. - **Values must be deterministic.** `DateTime.Now` or `Guid.NewGuid()` produce a different model on each build, so every `migrations add` scaffolds another `UpdateData`. - **Size matters.** The rows are written into the snapshot and every Designer file after them. ## UseSeeding and UseAsyncSeeding: code that runs on initialization Both are methods on `DbContextOptionsBuilder`: - `UseSeeding(Action<DbContext, bool> seed)`; - `UseAsyncSeeding(Func<DbContext, bool, CancellationToken, Task> seedAsync)`. The `bool` says whether any store operation was performed, such as creating the database or applying a migration. The delegate runs: | Operation | Delegate invoked | |---|---| | `EnsureCreated` or `Migrate` | `UseSeeding` | | `EnsureCreatedAsync` or `MigrateAsync` | `UseAsyncSeeding` | | `dotnet ef database update` | `UseSeeding` | | A migration bundle | `UseSeeding` | | A SQL script run by another tool | neither | Three rules follow: 1. **Check before inserting.** The delegate runs every time, even when nothing was pending, so it must query for existing rows. 2. **Configure both delegates.** If only `UseAsyncSeeding` is set, a synchronous path such as `dotnet ef database update` throws `InvalidOperationException` asking for an equivalent `UseSeeding` delegate; with only `UseSeeding`, `MigrateAsync` throws in the same way. 3. **Guard against missing tables** if you ever migrate down: seeding also runs after a downgrade. ## Choosing for a car-rental schema | Data | Mechanism | Why | |---|---|---| | Car categories, fuel policies, country codes | `HasData` | Small, fixed, keyed by known ids, changed only through migrations | | A default head-office branch whose id the database generates | `UseSeeding` | Needs a generated key and an existence check | | Admin users created through Identity's user manager | `UseSeeding` or startup code | Needs services and hashing, not literal values | | Demo rentals for local development | `UseSeeding` behind an environment check | Not reference data; must never reach production | ## Hand-written alternatives The operations `HasData` produces can also be written into a migration by hand: `migrationBuilder.InsertData`, `UpdateData` and `DeleteData` with explicit keys, or `migrationBuilder.Sql` when values come from existing rows. That keeps reference rows reviewable as SQL without putting them in the model, at the cost of maintaining them yourself. ## Traps that show up in interviews - **Seeding inside `OnModelCreating` with a query.** `HasData` takes literal objects; the model is built without a database, so nothing there can read existing rows. - **Seeding through `UseSeeding` and expecting a script deployment to carry it.** Scripts contain migration operations only. - **Seeding a large catalogue with `HasData`.** Thousands of rows end up in the snapshot and in every later Designer file, slowing builds and bloating diffs; load such data with `UseSeeding` or a separate import. - **Forgetting the `Down`.** A hand-written `InsertData` needs a `DeleteData` with the same keys in `Down`, or a revert leaves orphan rows behind.
- Why does seeding with DateTime.Now in HasData produce a new migration every time?HasData values are part of the model, and `migrations add` compares the model with the snapshot. A value computed at build time differs on every run, so the diff always finds a changed row and scaffolds another `UpdateData`. Use a fixed literal, or move time-dependent rows to `UseSeeding`.
- Do UseSeeding delegates run when a DBA applies a generated SQL script?No. Seeding delegates run only when EF Core itself creates or migrates the database: `EnsureCreated`, `Migrate`, `dotnet ef database update` or a bundle. A SQL script carries only migration operations, including `InsertData` from `HasData`, so data needed by a script-based deployment has to live in the migrations.
HasData is the printed menu: a dish changes only when a new edition is printed, which is the migration. UseSeeding is the cook checking the fridge every morning and restocking only what is missing.
- HasData lets the database generate the key, like a normal insert.
- Migrate re-applies the current HasData values on every startup.
- UseSeeding runs only when a migration was actually applied.
- Configuring UseAsyncSeeding alone is enough for dotnet ef database update.
- HasData is the right place for test users created with DateTime.Now.
Assumes EF Core 10; UseSeeding and UseAsyncSeeding arrived in EF Core 9, and before that HasData and hand-written startup code were the only built-in options.