C# Question

purpose of Database.SetInitializer<ArContext>(null) inside of repository?

I am using entity framework and in my context inheriting from DbContext.

public class MyContext : DbContext, IMyContext
{
static MyContext()
{
Database.SetInitializer<MyContext>(null);
}
//other stuff
}


What is the purpose of this line?

Database.SetInitializer<ArContext>(null)

Answer

You can turn off the DB initializer of your application. On the production environment where you don't want to lose the existing data.In such scenario you can turn off the initializer, as shown below.

 public MyContext()
    {
        Database.SetInitializer<MyContext>(null);//Disable initializer
    }

There are four different database initialization strategies:

  1. CreateDatabaseIfNotExists: This is 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, then it will throw an exception.
  2. DropCreateDatabaseIfModelChanges: This initializer drops an existing database and creates a new database, if your model classes (entity classes) have been 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 fresh database, every time you run the application, like while you are developing the application.
  4. Custom DB Initializer: You can also create your own custom initializer, if any of the above doesn't satisfy your requirements or you want to do some other process that initializes the database using the above initializer.

You can read it here too : Database Initialization Strategies

Comments