Please help Ukrainian armed forces! Official Fundraising

Database Initialization Strategies in EF 6 Code-First

1 1 1 1 1 Database Initialization Strategies in EF 6 Code-First5.00Rating 5.00 (1 Vote)

If you need to create database for your EF6 application you will need to think about initialization strategy. How to ensure the correct initialization of the database for the first time and also ensure it will not be re-created second time onwards? How to ensure it won't create a new database every time the ASP.NET Core application run? How can we deploy one database for a debug environment and another database for production environment? Entity Framework Does provide several strategies for database creation. They are called the database initialization strategies.

Let's look at possible database context initialization strategies:

CreateDatabaseIfNotExists: This is the behaviour by default. This strategy will re-create the database if none exists. The problem with this option is that if you change any model class and then re-launch your ASP.NET Web app with this initializer set, then it will throw an exception.
DropCreateDatabaseIfModelChanges: This initializer entirely deletes (DROP DATABASE) an existing database and creates a new one from scratch. It does so if the model classes (entities) have been changed even slightly. So, you don't have to think about maintaining your database schema, when your model classes change. But it will also delete all the data which may be available in the database already. This may be useful for debugging purposes or some simple applications.
DropCreateDatabaseAlways: This drop initializer DROPS an existing database every single time you run the application, and doesn't take into account of whether your model classes have changed or not. This might be useful when you want to debug your application. Can't imagine any uses of this strategy in a production envireonment.
Custom DB Initializer: You can also create your custom initialiation strategy. This is useful if you want to preserve data from backup or use your own import scripts. The production will most likely use this.

Friday the 11th.