Seeding data
Seeding puts starting data into the database, such as categories, countries or an admin role. This lesson compares HasData seeding through migrations with the UseSeeding methods added in EF Core 9, and shows when to use each.
- HasDataSmall fixed lists with known ids; lives in migrations
- UseSeedingCode that checks and adds data; EF Core 9+
- Startup scriptDemo data in development only
- Bulk importLarge data sets; outside EF seeding
Two kinds of seed data
Reference data that every environment needs, such as order statuses or countries, should be the same everywhere and change only with a release.
Sample or test data, such as demo products, belongs only in development and must never reach production.
HasData: seed through migrations
HasData stores rows in the model. The next migration contains INSERT, UPDATE or DELETE statements to match. Keys must be given explicitly, and it suits small, fixed lists.
modelBuilder.Entity<OrderStatus>().HasData(
new OrderStatus { Id = 1, Name = "New" },
new OrderStatus { Id = 2, Name = "Paid" },
new OrderStatus { Id = 3, Name = "Shipped" });
// dotnet ef migrations add SeedStatuses
// The migration contains InsertData(...) callsUseSeeding: seed with code (EF Core 9+)
UseSeeding and UseAsyncSeeding run when EnsureCreated or Migrate runs (and with dotnet ef database update). Your code can check what already exists, use generated keys and add related data. Write it so it is safe to run many times.
builder.Services.AddDbContext<ShopContext>(o => o
.UseSqlServer(connectionString)
.UseAsyncSeeding(async (context, _, ct) =>
{
var db = (ShopContext)context;
if (!await db.Categories.AnyAsync(ct))
{
db.Categories.AddRange(
new Category { Name = "Books" },
new Category { Name = "Stationery" });
await db.SaveChangesAsync(ct);
}
})
.UseSeeding((context, _) => { /* same logic, sync version for tools */ }));Tips
- Use HasData for small fixed lists with known ids; use UseSeeding for anything that needs logic.
- Keep demo data behind an environment check so it never runs in production.
- Changing HasData values creates a new migration that updates the rows.
- For large imports, use a script or bulk copy instead of seeding.
Interview question
When would you use HasData and when UseSeeding?
HasData suits small, fixed reference lists with known primary keys, because the rows become part of the model and every migration keeps them in sync. UseSeeding (EF Core 9 and later) suits seed data that needs logic, generated keys, related entities or checks against existing data, since it is ordinary code that runs during migration.
Want the full details? Read the official Microsoft documentation for this topic.