Home » Ado.Net » Entity Framework » DropCreateDatabaseIfModelChanges will create your database every time you start your application

DropCreateDatabaseIfModelChanges will create your database every time you start your application


DropCreateDatabaseIfModelChanges is an implementation of IDatabaseInitializer that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created.

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<Databa<a href="https://patrickdesjardins.com/blog/dropcreatedatabaseifmodelchanges-will-create-your-database-every-time-you-start-your-application/id-10022565" rel="attachment wp-att-1280"><img src="https://patrickdesjardins.com/blog/wp-content/uploads/2012/08/ID-10022565.jpg" alt="" title="ID-10022565" width="400" height="266" class="aligncenter size-full wp-image-1280" /></a>seContext>
{
    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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.