Seed Data in EF 6 Code-First

You can insert data into your database tables during the database initialization process. This will be important if you want to provide some test data for your application or some default master data for your application.

To seed data into your database, you have to create a custom DB initializer, as you created in the DB Initialization Strategy chapter, and override the Seed method. The following example shows how you can provide default data for the Standard table while initializing the School database:

public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
    protected override void Seed(SchoolDBContext context)
    {
        IList<Standard> defaultStandards = new List<Standard>();

        defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
        defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
        defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });

        context.Standards.AddRange(defaultStandards);

        base.Seed(context);
    }
}

Now, set this DB initializer class in context class as below.

public class SchoolContext: DbContext 
{
    public SchoolContext(): base("SchoolDB") 
    {
        Database.SetInitializer(new SchoolDBInitializer());
    }
    
    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
}