In this tutorial, we are going to look at Various Database initialization strategies that can be used in Entity Framework. The Database initialization strategy determines how the database is generated & updated when the underlying model changes. The entity framework provides us four strategies to handle these situations. Those strategies are Create database if not Exists, Create Database always, Drop and Create if Model changes and Custom DB Initialiser to handle the creation/updating of the database. We will take a look at how to use the Database.SetInitializer method to implement Database initialization strategies in Entity Framework.
Table of Contents
Database Initializer in Entity Framework
We created Entity Framework Code First Console Application & ASP.MVC Code First Application. Although we did not provide any connection string to the app, the EF figured it out and created and initialised the database for us. In the next tutorial, we learnt how to provide the connection string to our app
EF Creates the database if not exists when it is run. This is the default behaviour of EF. If the database already exists it does nothing and uses that database. But what will happen, if we change the domain class?. The database needs to be updated again right?. The entity framework does this using the database object.
Database Class
This class exists in the system.Data.entity namespace. This class manages the database and the connection to the database. This class has methods which allow us to create, delete or check for the existence of the Database. This class is implemented in DBcontext. You can get the instance of this class from the DBContext object.
The initialization of the database is done by the database class. It has a method called Initialize(Boolean) which is called by the DbContext to Initialize the database. It takes a boolean parameter (force). The initializer runs only when the context is used to access a database for the first time. If the force is set to true, then the initializer will run irrespective of whether it has run before.
Built In Database Initializers
The Entity Framework has provided three options to initialize the database.
- Create database if not Exists
- Create Database always
- Drop and Create if Model changes
Database.SetInitializer
The Database object runs the Initialize method. But we need to inform Database object, which initializer to run. This is done by Database.SetInitializer method
The following is the method signature of the Database.SetInitializer
1 2 3 4 5 | public static void SetInitializer<TContext>( IDatabaseInitializer<TContext> strategy ) where TContext : DbContext |
The SetInitializer must be called before the Context access the database. Hence it must be called in the constructor of the Context class.
The SetInitializer method takes any class that implements IDatabaseInitializer. The EF has three built- in implementation for the same. CreateDatabaseIfNotExists, DropCreateDatabaseAlways, DropCreateDatabaseIfModelChanges
Now let us explore all these options.
Create database if not Exists
This option will create the database if it does not exist. This is the default behaviour of Entity Framework Code first. If the model changes, then the application will throw an exception
1 2 3 4 5 6 | public EFContext() : base("EFDatabase") { Database.SetInitializer<EFContext>(new CreateDatabaseIfNotExists<EFContext>()); } |
The above code will create the database EFDatabase if it does not exist.
Create Database always
This option creates the database every time you run the application. If the database already exists, then it will drop and recreates it again. You will lose all the data existing in the database
1 2 3 4 5 6 | public EFContext() : base("EFDatabase") { Database.SetInitializer<EFContext>(new DropCreateDatabaseAlways<EFContext>()); } |
Drop and Create if Model changes
In this case, the database is recreated only when the model changes. You will lose all the data existing in the old database. This is useful when you are developing/testing your model.
1 2 3 4 5 6 | public EFContext() : base("EFDatabase") { Database.SetInitializer<EFContext>(new DropCreateDatabaseIfModelChanges<EFContext>()); } |
Custom DB Initializer
If any of the above methods do not satisfy your needs, then you can create the Custom initializer. We have covered this in our next tutorial Custom DB Initializer.
Turning off the Initialiser
You can easily turn off the DB initializer in your application by passing Null to the Database.SetInitializer method.
1 2 3 4 5 6 | public EFContext() : base("EFDatabase") { Database.SetInitializer<EFContext>(null); } |
Using Configuration file
The built-in initializers can also be set using the configuration file. These configurations are added under the section entityframework. The section entityFramework is automatically added to the configuration file when the Entity framework is installed. In the older versions of entity framework, these settings were added under the appSettings section. Starting from Version 4.3 the settings are moved to separate section entityframework in the configuration file. Entity Framework will still recognize database initializers set in the older format.
Database initializers are configured for each context. They are added to the configuration file under the context element. This element must use the fully qualified assembly name to identify the context being configured.
The following setting shows setting the Drop and Create if Model changes initializer in config file
1 2 3 4 5 6 7 8 9 | <entityFramework> <contexts> <context type="EFGettingStarted.EFContext, EFGettingStarted"> <databaseInitializer type="System.Data.Entity.DropCreateDatabaseAlways`1[[EFGettingStarted.EFContext, EFGettingStarted]], EntityFramework" /> </context> </contexts> </entityFramework> |
If database initializers are specified both in the code and the configuration file, then the initializer specified in the configuration file takes precedence
Disabling the database initialization
You can disable the database initialization using the disableDatabaseInitialization attribute on the context as shown below.
1 2 3 4 5 6 7 8 | <entityFramework> <contexts> <context type=" EFGettingStarted.EFContext, EFGettingStarted" disableDatabaseInitialization="true"> </context> </contexts> </entityFramework> |
You can read about the entity framework configuration file from this link
Conclusion
We have learnt how to initialize the database using the inbuilt initializers provided by the entity framework. If any of these initializers does not satisfy your requirement, then you can build your own Initializer, we are going to look at that in our next tutorial