DropCreateDatabaseIfModelChanges will create your database every time you start your application<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

DropCreateDatabaseIfModelChanges will create your database every time you start your application

Posted on: August 18, 2012

ID 10022565 150x150

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.

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

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.

1protected override void OnModelCreating(DbModelBuilder modelBuilder) {
2 Database.SetInitializer(new DatabaseContextInitializer());
4 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.