Click here to Skip to main content
12,695,404 members (26,879 online)
Click here to Skip to main content
Add your own
alternative version

Stats

46.8K views
10 bookmarked
Posted

Use of Database.SetInitializer() method in Code First

, 3 Sep 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
The use of different Database initializer options in Entity Framework Code First

What is the need of Database initializer?

The job of database initializer is to create the database and the specified tables. When a DbContext type is used to access database for the first time then the database initializer is called.

The Database.SetInitializer() method does this initialization operation. The following is the method signature(see documentation):

public static void SetInitializer(
IDatabaseInitializer strategy
)
where TContext : DbContext

The SetInitializer() method takes a parameter of IDatabaseInitializer<TContext> where the TContext is of DbContext type. DbContext is the light weight version of ObjectContext.

The IDatabaseInitializer<TContext> has three implementations: CreateDatabaseIfNotExists<TContext>, DropCreateDatabaseAlways<TContext>, DropCreateDatabaseIfModelChanges<TContext>

Explanation

  1. CreateDatabaseIfNotExists<TContext>: This is the default option. For the first time when the application runs the Entity Framework Code First creates database if it does not exist. If your database already exists and you have done some modification to the model and now you are running again the application, then you will get an exception of type InvalidOperationException.
  2. DropCreateDatabaseAlways<TContext>: As the name suggests it always drops and recreates the database when the application runs first time. It deletes all the tables as the database is dropped.
  3. DropCreateDatabaseIfModelChanges<TContext>: It drops and recreates the databases only when there is some changes or modifications in the model. Code First compare the version of in memeory model with that is stored in the _MigrationHistory table to know whether the Model is changed or not.

Note:

If you will call the Initialize() method immediately after creating a context instance then the database will be created immediately instead of waiting until the context is used for the first time. 

using (var context = new EducationContext())
{
    context.Database.Initialize(false);
}

The Initialize() method takes a boolean parameter to decide whether the initialization process should re-run. If  you will pass false, then the initialization process will skip if it has already executed. A value of true will initialize the database again even if it was already initialized. This is useful if a database is deleted while an application is running and it requires the database to be reinitialized.

If you use an existing database with Code First, you may not want to execute any initialization logic at all. You can disable the database initialization process altogether by passing null to SetInitializer() method.

Database.SetInitializer<EducationContext>(null);

Custom Database Initialization

You can create your custom IDatabaseInitializer<TContext> by implementing any of the above three options as follows:

public class MyDbInitializer : DropCreateDatabaseAlways<EducationContext>
{
    protected override void Seed(EducationContext context)
    {
        var student1  = new Student { Name = "Name 1" };
        var student2  = new Student { Name = "Name 2" };

        context.Students.Add(student1);
        context.Students.Add(student2);
        context.SaveChanges();
    }
}

Database.SetInitializer<EducationContext>(new MyDbInitializer());

The Seed() method is used when you want to insert some initial values to some tables. For example, if you have a look up table then you can insert the look up data by this Seed(TContext) method. This Seed(TContext) method will execute after the database tables are created.

Where to keep Database.SetInitializer() method?

The Database.SetInitializer() method should be kept before the Context object is initialized. In ASP.NET web application the best place will be in Application_Start() event of Global.asax file.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dukhabandhu Sahoo
Software Developer (Senior)
India India
I have been working with ASP.NET Web Technology for 4+ years(as on Oct 2015).

I have developed web applications which uses ASP.NET Web Forms, Web API, Entity Framework, SQL Server, LINQ, C#, jQuery, BootStrap UI and few other related libraries and tools.

Apart from programming, I love to watch cricket matches.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionMVC project no Global.asax file Pin
Rok Banko2-Jun-16 6:00
memberRok Banko2-Jun-16 6:00 
QuestionWhere do you store the custom initializer code Pin
zonkerman225-Oct-15 5:24
memberzonkerman225-Oct-15 5:24 
QuestionTurning off the initializer Pin
Dammie212-Jun-15 3:08
memberDammie212-Jun-15 3:08 
QuestionWhat is the meaning of SetInitializer(null)? Pin
Member 100736175-Sep-14 5:34
memberMember 100736175-Sep-14 5:34 
AnswerRe: What is the meaning of SetInitializer(null)? Pin
Dukhabandhu Sahoo9-Sep-14 5:13
professionalDukhabandhu Sahoo9-Sep-14 5:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170118.1 | Last Updated 3 Sep 2014
Article Copyright 2014 by Dukhabandhu Sahoo
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid