Entity Framework Code-first default data in database

Shawn Mclean picture Shawn Mclean · Apr 13, 2011 · Viewed 32.3k times · Source

How do I handle situations in which I need pre-existing data before the app is started or right after the database is generated. For example, I have a list of countries in which I'd like to load into the database after code-first generates it. How do I do this?

App is structured as follows:

Repository > Service > WebMVC

The xml is in the WebMVC project.

Answer

Damb picture Damb · Apr 13, 2011

You create custom initializer, which inherits from DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways interface. Like:

public class EntitiesContextInitializer : DropCreateDatabaseIfModelChanges<-YourDbContext->

And then you overwrite Seed method like:

protected override void Seed(YourDbContext context)

Whole example might look like:

public class EntitiesContextInitializer : DropCreateDatabaseIfModelChanges<EntitiesContext>
{
    protected override void Seed(EntitiesContext context)
    {
        List<Role> roles = new List<Role>
        {
            new Role {Id=1, Title="Admin"},
            new Role {Id=2, Title="ProjectManager"},
            new Role {Id=3, Title="Developer"}
        };

        // add data into context and save to db
        foreach (Role r in roles)
        {
            context.Roles.Add(r);
        }
        context.SaveChanges();

    }
}

Edit: After setting this up, you have to set up Initializer too, as Ladislav Mrnka mentioned.

Database.SetInitializer(new EntitiesContextInitializer());

ie.: in Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    Database.SetInitializer(new EntitiesContextInitializer());
}

Don't forget to add using System.Data.Entity; .....