Database Initialization in EF


Database Initialization in EF

You already created a database after running your Code-First application the first time, but what about the second time? Will it create a new database every time you run the application? What about the production environment? How do you alter the database when you change your domain model? To handle these scenarios, you have to use one of the database initialization strategies.

There are four different database initialization strategies:

  1. CreateDatabaseIfNotExists: This is the default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, if you change the model class and then run the application with this initializer, it will throw an exception.
  2. DropCreateDatabaseIfModelChanges: This initializer drops an existing database and creates a new one if your model classes (entity classes) have changed. So, you don't have to worry about maintaining your database schema when your model classes change.
  3. DropCreateDatabaseAlways: As the name suggests, this initializer drops an existing database every time you run the application, irrespective of whether your model classes have changed or not. This will be useful when you want a fresh database every time you run the application, for example, when developing the application.
  4. Custom DB Initializer: You can also create your custom initializer if the above does not satisfy your requirements or you want to do another process that initializes the database using the above initializer.

Turn off the DB Initializer

You can turn off the database initializer for your application. Suppose that you don't want to lose existing data in the production environment, then you can turn off the initializer,