Patrick Desjardins Blog
Patrick Desjardins picture from a conference

DropCreateDatabaseIfModelChanges will create your database every time you start your application

Posted on: 2012-08-18

That mean that if you are developing something and want to have the database updated to your model changes that you need to create your class that inherit DropCreateDatabaseIfModelChanges . This implementation require you to use the type of the Database Context because it's a generic class. The class that you will create will inherit from DropCreateDatabaseIfModelChanges.

public class DatabaseContextInitializer : DropCreateDatabaseIfModelChanges<Database>
{
  
  protected override void Seed(DatabaseContext dbContext) { 
    // seed data 
    base.Seed(dbContext);
  } 
} 

Once created, you need to set the DbContext to know about this Initializer. This is done by setting it inside the OnModelCreating of your DbContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder) { 
  Database.SetInitializer(new DatabaseContextInitializer());

  base.OnModelCreating(modelBuilder); 
} 

You can set inside Seed some alter table statement or anything you want to be loaded into the database.

The DropCreateDatabaseIfModelChanges should only be used on the development machine because in production it will cause the suppression of all your real data when the model change.

They are also the implementation called DropCreateDatabaseAlways which will drop every time the context is initialized. This is also only good for development purpose.

What is the goal of using database context initializer?

The goal is to create all your model inside the code and let Entity Framework create for you the database. This is why it's called "Code First" approach because you work on the classes and let Entity Framework handle the database. Once it's create, you can remove the statement and deploy.