📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you seed data in EF Core 10? Explain HasData, the UseSeeding and UseAsyncSeeding methods added in EF Core 9, and how you treat reference data differently from test or demo data.

Seeding in EF Core 10: model-managed HasData, UseSeeding/UseAsyncSeeding, custom initialisation, and keeping reference, test and demo data separate.

Junior Theory Intermediate ef-core hasdata migrations reference-data seed-data testing

🎯 Key points

  • HasData is model-managed seeding: rows become part of migrations as InsertData, UpdateData and DeleteData
  • HasData needs explicit primary key values and constant data; it cannot query the database or use navigations directly
  • UseSeeding and UseAsyncSeeding (added in EF Core 9, still the recommended general-purpose seeding API in EF Core 10) run from EnsureCreated, Migrate and dotnet ef database update; implement both
  • Custom seeding runs under the migration lock EF Core 9+ takes, but must still be idempotent: check before inserting
  • Reference data (countries, statuses, currency codes) belongs in migrations or seeding and ships to every environment, which keeps environments consistent
  • Test and demo data never goes to production; create it in test fixtures or a separate environment-gated seeder
  • When the schema changes, update HasData rows in the same migration; large or frequently changing data is better loaded by a script or import job

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Seeding means putting known data into the database so the app works, and EF Core gives you two tools. The older one is HasData in OnModelCreating. 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 generates InsertData, UpdateData or DeleteData. 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 UseSeeding and UseAsyncSeeding. You register them when you configure the context, and EF Core calls them from EnsureCreated, Migrate and dotnet 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."


The options

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 vs test data

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows both seeding mechanisms and keeps production reference data separate from test data.

Green flags

  • Explains that HasData rows become InsertData/UpdateData in migrations
  • Knows UseSeeding/UseAsyncSeeding and that both should be implemented
  • Writes idempotent seeding code
  • Keeps test and demo data out of production

Red flags

  • Seeding in Program.cs on every start-up with no checks
  • Fake users or real customer data in migrations

📚 Learn in depth

1. How HasData works

OnModelCreating: 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.

2. UseSeeding and UseAsyncSeeding

options.UseSqlServer(cs)
       .UseSeeding((context, storeOperationPerformed) => { ... })
       .UseAsyncSeeding(async (context, storeOperationPerformed, ct) => { ... });
  • storeOperationPerformed tells you whether EnsureCreated or Migrate actually changed something.
  • They run inside the migration lock that EF Core 9 introduced for Migrate, so two instances do not seed at once.
  • Implement both: the dotnet ef tools run the synchronous path, while MigrateAsync runs the async one.

3. Idempotency

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.

4. Where seeding goes wrong

  • Seeding inside Program.cs on every start-up of every instance: slow cold starts and race conditions.
  • Seeding personal information or real customer data copied from production: a Privacy Act problem in test environments.
  • Seeding default admin users with known passwords: a security finding.
  • Huge HasData sets (thousands of rows): bloated snapshots and slow model building. Load these with a script.

Try it yourself

  1. Add HasData for an OrderStatus lookup, create a migration and read the InsertData call.
  2. Change one status name and see the UpdateData it generates.
  3. Add UseSeeding and UseAsyncSeeding, run dotnet ef database update twice, and confirm nothing duplicates.
  4. Put DateTime.Now in a HasData row and watch EF Core report pending model changes.

💻 Code

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" } });

⚠ Common mistakes

  • Mistake: Using 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.
  • Mistake: Seeding test customers or admin users with known passwords in 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.
  • Mistake: Writing 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.
  • Mistake: Implementing only UseAsyncSeeding. Why it is wrong: dotnet ef database update uses the sync path, so seeding silently does not happen there. Instead: Implement both.
  • Mistake: Putting thousands of rows in HasData. Why it is wrong: It bloats the snapshot and slows model building. Instead: Load large data with a script or import job.
  • Mistake: Copying production data into test databases to "seed" them. Why it is wrong: It moves personal information into less protected environments, a Privacy Act risk. Instead: Generate synthetic data (for example with Bogus).

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions migrations running in the pipeline Why: Checks how seeding and migrations are applied in CI/CD
    How to answer

    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.

  2. When: Candidate mentions keeping test data separate Why: Checks synthetic data generation and Privacy Act awareness
    How to answer

    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.

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me