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

Seed Data Configuration

Populate static lookup data using migration-based seeding strategies.

In this lesson, you will learn how to automate the insertion of static lookup data into your database using Entity Framework Core migration-based seeding.

Why Use Data Seeding?

Often, your application relies on "lookup data"—information that must exist for the system to function, such as status codes (Pending, Active, Archived) or default configuration settings. While you could insert these manually, migration-based seeding ensures that every developer on your team and every environment (development, staging, production) has the exact same baseline data as soon as the schema is created.

How to Seed Data

EF Core provides the HasData method within the Fluent API. You use this inside your OnModelCreating override. When you run Add-Migration, EF Core compares the data you defined in your model against the current state of the database and generates the necessary INSERT, UPDATE, or DELETE statements.

Here is how you populate a Status lookup table:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Status>().HasData(
        new Status { Id = 1, Name = "Pending" },
        new Status { Id = 2, Name = "Active" },
        new Status { Id = 3, Name = "Archived" }
    );
}

Critical Rules for Seeding

  1. Define the Primary Key: When using HasData, you must explicitly provide the primary key value. Even if your database uses an identity column for auto-incrementing IDs, EF Core needs these explicit values to track the data and determine if it needs to update an existing record or insert a new one.
  2. Migration Coupling: Because HasData is part of your model definition, it is intrinsically tied to your migrations. If you change a value in the HasData call and run a new migration, EF Core will generate a migration that updates the existing data in your database to match your new definition.
  3. Use for Static Data Only: This approach is intended for structural lookup data. It is not suitable for populating large volumes of data or dynamic user-generated content, as those are better handled via initialization scripts or background services.

Key Takeaway: Use the HasData method within OnModelCreating to define your application's required lookup data, ensuring consistent database state across all environments through your migration history.