Listen to this Post

EF Core 9 has simplified database seeding, eliminating the need to override `OnModelCreating` or manually handle seeding scripts. Here’s how you can leverage these improvements.
Basic Seeding in EF Core 9
Instead of traditional methods, EF Core 9 introduces a cleaner approach:
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasData(
new Product { Id = 1, Name = "Laptop", Price = 999.99 },
new Product { Id = 2, Name = "Mouse", Price = 19.99 }
);
}
}
Async Seeding Support
EF Core 9 now supports async seeding for better performance:
protected override async Task OnModelCreatingAsync(ModelBuilder modelBuilder)
{
await modelBuilder.Entity<Customer>().HasDataAsync(
new Customer { Id = 1, Name = "John Doe" },
new Customer { Id = 2, Name = "Jane Smith" }
);
}
Using Scoped Services in Seeding
EF Core 9 allows dependency injection during seeding:
protected override async Task OnModelCreatingAsync(ModelBuilder modelBuilder, IServiceProvider serviceProvider)
{
var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
var adminUser = new IdentityUser { UserName = "[email protected]", Email = "[email protected]" };
await userManager.CreateAsync(adminUser, "SecurePassword123!");
}
You Should Know: Essential Commands for Seeding & Database Management
1. Applying Migrations & Seeding Data
dotnet ef database update
2. Generating a New Migration
dotnet ef migrations add InitialCreate
3. Resetting the Database
dotnet ef database drop dotnet ef database update
4. Checking Pending Migrations
dotnet ef migrations list
5. Using EF Core CLI Tools
Ensure you have the tools installed:
dotnet tool install --global dotnet-ef
6. Seeding with External Data (JSON/CSV)
var products = JsonSerializer.Deserialize<List<Product>>(File.ReadAllText("products.json"));
modelBuilder.Entity<Product>().HasData(products);
7. Handling Production Seeding
Use environment checks:
if (env.IsProduction())
{
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.Migrate();
await SeedData.InitializeAsync(db);
}
What Undercode Say
EF Core 9 makes database seeding more intuitive by supporting async operations and dependency injection. Key takeaways:
– Use `HasData` for static data.
– Prefer async seeding for performance.
– Leverage scoped services for dynamic seeding.
– Always test migrations before production deployment.
For further learning, check the .NET Web API Zero to Hero Course.
Expected Output:
A fully seeded database with structured, maintainable, and testable data initialization in .NET apps.
Verify seeded data dotnet ef dbcontext info
Use these techniques to streamline your .NET development workflow. 🚀
References:
Reported By: Iammukeshm This – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


