EF Core Seed Data — Complete Guide
In this tutorial, you'll learn about EF Core Seed Data. We cover key concepts, practical examples, and best practices.
Your application needs initial data — reference values, admin users, default categories. You write a SQL script that runs during deployment, but it drifts from your model. EF Core seeding lets you populate data as part of the migration or application startup.
Wrong
// Manual SQL script that doesn't match the model
// INSERT INTO Categories VALUES ('Electronics', 'Books', 'Clothing')
// — hard to maintain, no type safety
Output: Script runs but silently fails if columns change. No compile-time checking.
Right
Model seed data in migration configuration:
public class AppDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>().HasData(
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Books" },
new Category { Id = 3, Name = "Clothing" }
);
}
}
Add a migration to apply seed data:
dotnet ef migrations add SeedCategories
For application startup seeding (development only):
public static async Task SeedAsync(AppDbContext db)
{
if (!await db.Categories.AnyAsync())
{
db.Categories.AddRange(
new Category { Name = "Electronics" },
new Category { Name = "Books" }
);
await db.SaveChangesAsync();
}
}
Prevention
- Use
HasData()inOnModelCreatingfor seed data in migrations. - Specify explicit primary key values in
HasData()— EF Core needs them for diff tracking. - Use
EnsureCreated()only for prototyping — not for production seeding. - Use dedicated seed methods in
Program.csfor development data. - Do not seed data in every migration — create one seed migration per dataset.
- Consider JSON files or configuration for large seed datasets.
- Use
db.Database.EnsureCreated()followed by seeding for new databases.
Common Mistakes with core seed data
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Learn more about EF Core data seeding at DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro