Seeding Data in ASP.NET Core with EF Core
What is Seeding?
Seeding provides a way to populate a database with initial data when the application starts. This is useful for default records, test data, or demo environments.
Define Seed Data
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>());
if (context.Books.Any()) return;
context.Books.AddRange(
new Book { Title = "ASP.NET Core in Action", Author = "Andrew Lock", Price = 39.99M },
new Book { Title = "Entity Framework Core Cookbook", Author = "Julie Lerman", Price = 44.99M }
);
context.SaveChanges();
}
}
Register the Seeder
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
SeedData.Initialize(services);
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
Running Migrations
Ensure the database schema matches the model before seeding:
dotnet ef migrations add InitialCreate
dotnet ef database update
Testing the Seed
Launch the app and navigate to /api/books (or any endpoint that returns the seeded entities). You should see the two books added above.