Seeding in EF Core 10: model-managed HasData, UseSeeding/UseAsyncSeeding, custom initialisation, and keeping reference, test and demo data separate.
EF Core has two main ways to seed.
HasData in OnModelCreating is model-managed: the rows become part of the model, and migrations emit InsertData, UpdateData or DeleteData when they change. It needs fixed primary keys and constant values.UseSeeding / UseAsyncSeeding (EF Core 9+) are callbacks on DbContextOptionsBuilder that run your own code when EnsureCreated, Migrate or dotnet ef database update runs. They can query first, so they must be written to be idempotent.Use seeding for reference data that production needs (statuses, countries). Keep test and demo data out of migrations and in test fixtures. The trade-off: HasData is versioned and reviewable but rigid; custom seeding is flexible but you own idempotency.
"Seeding means putting known data into the database so the app works, and EF Core gives you two tools. The older one is
HasDatainOnModelCreating. You declare rows with explicit key values, and EF Core treats them as part of the model. When you add a migration, it compares the seeded rows with the snapshot and generatesInsertData,UpdateDataorDeleteData. That makes reference data versioned and reviewed like schema, which is great for small, stable lists such as order statuses or Australian states.The newer one, added in EF Core 9, is
UseSeedingandUseAsyncSeeding. You register them when you configure the context, and EF Core calls them fromEnsureCreated,Migrateanddotnet ef database update. Inside you have a normal context, so you can query, use navigations and generated keys. The catch is that EF Core doesn't track what you've already inserted, so the code must check first. Microsoft recommends implementing both, because the tools call the sync one and the app usually calls the async one.The mistake I see is mixing kinds of data. Reference data the app needs belongs in migrations or seeding and ships everywhere. Test and demo data, like fake customers, belongs in test fixtures or a seeder that only runs in development. I've seen demo users with known passwords end up in production because they were in
HasData. Seed what production needs, and nothing else."
| Approach | How it runs | Good for | Limits |
|---|---|---|---|
HasData |
Generated into migrations | Small, static reference data | Explicit keys, constants, no queries |
UseSeeding / UseAsyncSeeding |
Called by EnsureCreated, Migrate, database update |
Data needing logic or generated keys | You write idempotency |
| Custom initialiser at start-up | Your own code | Legacy pattern | Runs on every instance; avoid in production |
| SQL script or import job | Pipeline or tool | Large or frequently changing data | Outside EF Core's model |
| Test fixtures | Per test | Test data | Never in production |
| Reference data | Test or demo data | |
|---|---|---|
| Examples | Order statuses, currencies, Australian states | Fake customers, sample orders |
| Environments | All, including production | Development, test only |
| Where it lives | HasData or seeding |
Test project, dev-only seeder |
In a [freight booking system] we moved [about 30] lookup tables from a hand-run SQL file into HasData. Environment drift bugs ("status 7 doesn't exist in UAT") dropped to [zero], and every change to reference data appeared in a pull request as an InsertData or UpdateData call.
Checks that the candidate knows both seeding mechanisms and keeps production reference data separate from test data.
Green flags
HasData rows become InsertData/UpdateData in migrationsUseSeeding/UseAsyncSeeding and that both should be implementedRed flags
Program.cs on every start-up with no checksOnModelCreating: HasData(rows)
│
▼
Model snapshot stores the rows
│ dotnet ef migrations add
▼
Diff: new row → InsertData, changed → UpdateData, removed → DeleteData
Because seeded rows are compared by primary key, you must supply keys yourself, even for identity columns (EF Core enables identity insert for those statements). Values must be constants: DateTime.Now or Guid.NewGuid() would change the model on every build and cause a new migration each time (EF Core 9+ also warns about pending model changes when this happens).
For related data, set the foreign key value rather than a navigation. For owned types, call HasData on the owned builder.
options.UseSqlServer(cs)
.UseSeeding((context, storeOperationPerformed) => { ... })
.UseAsyncSeeding(async (context, storeOperationPerformed, ct) => { ... });
storeOperationPerformed tells you whether EnsureCreated or Migrate actually changed something.Migrate, so two instances do not seed at once.dotnet ef tools run the synchronous path, while MigrateAsync runs the async one.Custom seeding runs every time a migrate command runs. Write it as "ensure exists": query by a natural key, insert only if missing. For larger reference sets, a MERGE script or a set-based upsert is clearer.
Program.cs on every start-up of every instance: slow cold starts and race conditions.HasData sets (thousands of rows): bloated snapshots and slow model building. Load these with a script.HasData for an OrderStatus lookup, create a migration and read the InsertData call.UpdateData it generates.UseSeeding and UseAsyncSeeding, run dotnet ef database update twice, and confirm nothing duplicates.DateTime.Now in a HasData row and watch EF Core report pending model changes.Reference data with HasData and idempotent custom seeding with UseSeeding/UseAsyncSeeding:
namespace Freight.Infrastructure;
using Microsoft.EntityFrameworkCore;
public sealed class OrderStatus
{
public int Id { get; init; }
public required string Name { get; init; }
}
public sealed class Depot
{
public int Id { get; set; }
public required string Code { get; init; }
public required string State { get; init; }
}
public sealed class FreightDbContext(DbContextOptions<FreightDbContext> options) : DbContext(options)
{
public DbSet<OrderStatus> OrderStatuses => Set<OrderStatus>();
public DbSet<Depot> Depots => Set<Depot>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Model-managed: explicit keys and constants, generated into migrations.
modelBuilder.Entity<OrderStatus>().HasData(
new OrderStatus { Id = 1, Name = "Booked" },
new OrderStatus { Id = 2, Name = "InTransit" },
new OrderStatus { Id = 3, Name = "Delivered" });
}
}
// Program.cs
builder.Services.AddDbContext<FreightDbContext>(options => options
.UseSqlServer(builder.Configuration.GetConnectionString("Freight"))
// Sync version: used by dotnet ef database update and EnsureCreated.
.UseSeeding((context, _) =>
{
if (!context.Set<Depot>().Any(d => d.Code == "SYD1"))
{
context.Set<Depot>().Add(new Depot { Code = "SYD1", State = "NSW" });
context.SaveChanges();
}
})
// Async version: used by MigrateAsync and EnsureCreatedAsync. Implement both.
.UseAsyncSeeding(async (context, _, ct) =>
{
if (!await context.Set<Depot>().AnyAsync(d => d.Code == "SYD1", ct))
{
context.Set<Depot>().Add(new Depot { Code = "SYD1", State = "NSW" });
await context.SaveChangesAsync(ct);
}
}));
The migration EF Core generates for the HasData rows:
migrationBuilder.InsertData(
table: "OrderStatuses",
columns: ["Id", "Name"],
values: new object[,] { { 1, "Booked" }, { 2, "InTransit" }, { 3, "Delivered" } });
Guid.NewGuid() or DateTime.Now in HasData. Why it is wrong: The model changes on every build, so every migrations add produces a spurious UpdateData. Instead: Use fixed constant values.HasData. Why it is wrong: Migrations run in production, so the fake data and credentials go there too. Instead: Keep test data in fixtures or a development-only seeder.UseSeeding code that inserts unconditionally. Why it is wrong: It runs on every migrate command and duplicates rows. Instead: Check by a natural key before inserting.UseAsyncSeeding. Why it is wrong: dotnet ef database update uses the sync path, so seeding silently does not happen there. Instead: Implement both.HasData. Why it is wrong: It bloats the snapshot and slows model building. Instead: Load large data with a script or import job.As of EF Core 10 (the current LTS, released November 2025) there is no new seeding API: HasData and UseSeeding/UseAsyncSeeding are still the two recommended mechanisms, and the EF Core 9 changes around them (the migration lock and the pending-model-changes error that non-constant HasData values trigger) still apply. What matters more than the API is discipline.
I keep three buckets strictly apart: reference data (ships everywhere, versioned, so every environment has the same lookups), configuration data (often per environment, better in configuration or an admin screen), and test data (never in production). Most seeding bugs come from mixing them. When a schema change touches a seeded table, the HasData rows change in the same migration so data and schema stay consistent.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
HasData |
Small, static lookups | Explicit keys, migration noise when edited | Large or computed data |
UseSeeding / UseAsyncSeeding |
Data needing queries or generated keys | You own idempotency | Data that must be reviewed row by row |
| Script / import job | Large reference sets (postcodes) | Outside EF Core | Tiny lookups |
I generate migrations locally with dotnet ef migrations add, then make deployment a separate, reviewed step. The pipeline produces an artefact: either an idempotent SQL script (dotnet ef migrations script --idempotent) for a DBA to review, or a migration bundle (dotnet ef migrations bundle), a self-contained executable that applies pending migrations. That artefact runs once, before the new app version starts, with a dedicated deployment identity. I avoid Database.Migrate() at startup because several instances can race, the app needs DDL permissions it shouldn't have, and a failed migration turns into a crash loop.
Use a library such as Bogus to generate synthetic but realistic data with a fixed seed, so runs are reproducible. Create it per test or per fixture against a real SQL Server in a Testcontainers container, and reset between tests (Respawn or a transaction rolled back at the end). Never copy production data into test environments: it moves personal information into less protected places, which is a Privacy Act and Notifiable Data Breaches risk. When you need production-like volumes, generate them, or use a masked copy approved by the data owner.
Last updated 23 Nov 2026.