Course contentsShow
← C#
Lesson 1126 of 1,90810. Entity Framework Core ModelingFree lesson

Managing Data Seeding

Create reproducible environmental setups using automated seed initialization logic.

In this lesson, you will learn how to automate the initialization of your database with reproducible, environment-specific data using EF Core’s HasData method.

Why Automate Seeding?

When working in a team or deploying across multiple environments (Development, Staging, Production), you cannot rely on manual SQL scripts. Manual seeding is prone to error and difficult to track. EF Core allows you to define "seed data" directly within your DbContext using the Fluent API. This ensures that every time you run a migration, the database state remains consistent and predictable.

Implementing Data Seeding

The most robust way to seed data is by using the HasData() method within your OnModelCreating override. This tells EF Core that these entities are "seed data," and the framework will manage their existence during migration updates.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Category>().HasData(
        new Category { Id = 1, Name = "Electronics" },
        new Category { Id = 2, Name = "Books" }
    );

    modelBuilder.Entity<Product>().HasData(
        new Product { Id = 1, Name = "Laptop", CategoryId = 1, Price = 999.99m }
    );
}

Key Considerations

  1. Primary Keys: When using HasData, you must provide explicit values for primary keys. EF Core tracks these entities; if you change a property value in your code, EF Core will generate a migration to update the existing record in the database.
  2. Environment Sensitivity: Sometimes you only want certain data in development (e.g., test users). Since OnModelCreating is standard C# code, you can use environment variables or configuration settings to conditionally include specific seed data.
  3. Data Integrity: Avoid seeding large amounts of complex production data this way. HasData is optimized for look-up tables (like Countries or Status codes) and mandatory initial configuration. For large-scale data imports, consider a post-deployment migration task or a dedicated service implementation.

By embedding this logic into your migration pipeline, your team ensures that every developer and server starts with the exact same foundational data, removing "it works on my machine" issues.

Key Takeaway: Use the HasData Fluent API to treat your seed data as code, ensuring that your database environment is consistently reproducible across all deployment stages.