Understanding Database Initializers in Entity Framework Code First

Entity Framework Code First allows you to create data model classes prior to creating a database. When you run the application for the first time, a database is created for you on the fly based on the classes you created. Database initializers allow you to decide a strategy of database creation and seed data generation. Code First provides its own set of database initializer classes and also allows you to create your own. In this article you will learn to use the inbuilt database initializers in your application. You will also learn to create your own database initializers. Additionally, the article will illustrate how to populate a database with seed data during the initialization process.


This article will not discuss the basics of Code First. If you are not familiar with Code First read Introduction to Entity Framework Code First. You will be using the same code sample in this article and we won't discuss the sample application in detail again.

What is Database Initialization?

A database initializer is a class that takes care of database creation and initialization in a Code First application. It is the job of database initializer to create the database and required tables based on the data model classes you create. To understand the role of database initializer, let's create a simple console application (see code download accompanying this article).

Have a look at the following model classes from the application:

public class BlogPost
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime PublishDate { get; set; }
    public Guid CategoryId { get; set; }
    public virtual Category Category { get; set; }
public class Category
   public Guid Id { get; set; }
   public string Name { get; set; }
   public virtual ICollection<BlogPost> BlogPosts { get; set; }

The BlogPost class represents a blog post and corresponds to a BlogPosts table as indicated by the [Table] attribute. Similarly, Category class represents a blog post category and corresponds to the Categories table. Also have a look at the BlogContext class that represents a database context:

public class BlogContext : DbContext
    public BlogContext():base()
    public DbSet<BlogPost> BlogPosts { get; set; }
    public DbSet<Category> Categories { get; set; }

The Main() method then makes use of these classes to add a record in both of the tables.

static void Main(string[] args)
    using (var db = new BlogContext())
        Guid postId = Guid.NewGuid();
        Guid catId = Guid.NewGuid();
        var cat = new Category { Id = catId, Name = "ASP.NET" };
        var post = new  BlogPost { Id=postId,Title="Title1", Content="Hello World!", PublishDate=new DateTime(2011,1,1), Category=cat};
        int i = db.SaveChanges();
        Console.WriteLine("{0} records added...", i);

If you run the application you will find a database created as shown below:

The database was created automatically
Figure 1: The database was created automatically

Notice that the database CodeFirstDbInitializerDemo.BlogContext was created automatically and contains two application tables viz. BlogPosts and Categories. There is also a metadata table - EdmMetadata - that stores model metadata. This all happened because of an inbuilt database initializer - CreateDatabaseIfNotExists. As the name suggests the default database initializer will create a database only if it doesn't exist. Now, manually delete the BlogPosts table and run the application again.

This time you will get an exception indicating that the already existing database was used and since it no longer has BlogPosts table the code throws an exception while saving the changes.

Figure 2: DbUpdateException

Available Database Initializers

Entity Framework Code First comes with three basic database initializers viz. CreateDatabaseIfNotExists, DropCreateDatabaseWhenModelChanges and DropCreateDatabaseAlways.


This is the default database initializer class used by Code First unless you specify some other class. As the name suggests, the CreateDatabaseIfNotExists class creates a database only if it doesn't exist. This initializer also comes in handy when you wish to avoid any accidental deletion of the database.


This database initializer creates a database if it doesn't exist already. Additionally, if a database is already present but there is a mismatch between the model classes and table schema then it deletes the database and re-creates it. You will find this more useful during development and testing when models are changing often.


The DropCreateDatabaseAlways class deletes and creates a database irrespective of whether it is already present or not. This way, with every run of the application you will be deleting and re-creating the database. You will find this initializer useful during testing when you want to run the application with a fresh set of data.

You can also create your own database initializer by implementing the IDatabaseInitializer interface. You will develop a custom database initializer in the later sections.

Using Inbuilt Database Initializers

Now that you are aware of the inbuilt database initializers provided by Code First, let's see how to use them in your application.

To use a particular database initializer add the following piece of code at the beginning of the Main() method:

Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());

The SetInitializer() method takes an instance of database initializer class and sets it as a database initializer for the current application domain. When you set a database initializer, it won't be called immediately. It will be called when the context (BlogContext) is used for the first time. In the preceding example, the actual database creation will occur only when you add a new Category and BlogPost and not when a new instance of BlogContext is created.

static void Main(string[] args)
    Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());
    using (var db = new BlogContext()) //initializer won't be called here
        db.Categories.Add(cat); //initializer will be called here

If you wish to use CreateDatabaseIfNotExists database initializer, you need not do anything specific since it is the default database initializer. Of course, you can set it explicitly using SetInitializer() method as shown above.

By default, Code First runs the database initialization logic once per AppDomain when the context is used for the first time. You can, however, override this default behavior using the Initialize() method. You may wish to call a database initializer explicitly when your model is complex and initialization is going to take more time to run. This way rather than spending time at some later stage you are running the initialization process at some known step (and can show a wait message to the end user). To use the Initialize() method you will need to modify your code as shown below:

Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());
using (var db = new BlogContext())

In the above code snippet you are calling the Initialize() method immediately after creating a context instance. In this case, the database will be created immediately after calling the Initialize() method instead of waiting until the context is used for the first time. The Initialize() method takes a boolean parameter that controls whether the initialization process should re-run if it has already run for the application. Specifying false will skip the initialization process if it has already executed. A value of true will initialize the database again even if it was already initialized.

At times you may want to use an existing database with Code First. In such cases you may not want to execute any initialization logic at all. You can suppress the database initialization process altogether by passing null to SetInitializer() method.


Seeding Data

During the testing phase you often need to populate database tables with sample data. At times you also need to populate some application data at the time of database creation. For example, while creating our sample database you may want to populate the Categories table with some predefined categories. Such seed data can be added to the database being created by overriding the Seed() method of the database initializer class. Consider the following piece of code :

public class BlogContextSeedInitializer : DropCreateDatabaseAlways<BlogContext>
    protected override void Seed(BlogContext context)
        Category cat1 = new Category { Id = Guid.NewGuid(), Name = ".NET Framework" };
        Category cat2 = new Category { Id = Guid.NewGuid(), Name = "SQL Server" };
        Category cat3 = new Category { Id = Guid.NewGuid(), Name = "jQuery" };

Here, you created a custom database initializer by inheriting DropCreateDatabaseAlways class. Further, you need to override the Seed() method. The Seed() method receives the context object as a parameter. You then create three categories and add them to the context. Finally SaveChanges() method saves the data to the database that was created during the initialization process.

To see the Seed() method in action, you need to use BlogContextSeedInitializer in the Main() method. Adding the following line of code will do that job:

Database.SetInitializer(new BlogContextSeedInitializer());

If you run the application again and check the Categories table, you should see sample data added to it.

Sample data added
Figure 3: Sample data added

Creating a Custom Database Initializer

In the preceding examples you used inbuilt database initializers. You can also create a custom database initializer by implementing the IDatabaseInitializer interface. You need to implement the InitializeDatabase() method of IDatabaseInitializer interface and write your own logic of database creation. The following code shows a sample implementation of the InitializeDatabase() method:

public class BlogContextCustomInitializer : IDatabaseInitializer<BlogContext>
    public void InitializeDatabase(BlogContext context)
        if (context.Database.Exists())
            if (!context.Database.CompatibleWithModel(true))
        context.Database.ExecuteSqlCommand("CREATE TABLE GLOBAL_DATA([KEY] VARCHAR(50), [VALUE] VARCHAR(250))");

The InitializeDatabase() method receives an instance of a content class. You can then use the Exists() method to determine whether a database is already present. The CompatibleWithModel() method tells you (true / false) whether the database schema is compatible with the model. If the database is not compatible you delete and recreate it using Delete() and Create() methods respectively. If no database exists then you create a new one using the Create() method. Notice how the code is using the ExecuteSqlCommand() method to create the GLOBAL_DATA table that is not part of the model. Though we don't use that table in our example it illustrates how custom initializers can be used to perform custom tasks.

Now, set the BlogContextCustomInitializer class as the initializer using the SetInitializer() method and run the application. You will find that in addition to model tables, the GLOBAL_DATA table is also created.

The GLOBAL_DATA table is created
Figure 4: The GLOBAL_DATA table is created

Specifying Database Initializer in Configuration File

In all of the preceding examples you specified a database initializer in the code itself. You can also specify it in the application configuration file by adding a key in the <appSettings> section. This technique can be useful if you are switching between database initializers often. The <appSettings> key and value must be in a specific format as shown in the following markup:

 <add key="DatabaseInitializerForType CodeFirstDbInitializerDemo.BlogContext,CodeFirstDbInitializerDemo"

     value="CodeFirstDbInitializerDemo.BlogContextCustomInitializer, CodeFirstDbInitializerDemo" />

Notice the key carefully. It must begin with a predefined value DatabaseInitializerForType followed by a white space and then followed by the assembly qualified name of the context class. The first part of the assembly qualified name is of the form MyNamespace.MyContextClass and the second part is the name of the assembly that contains the context class (CodeFirstDbInitializerDemo). The value is an assembly qualified name of custom database initializer class.

To see the above setting in action, comment out the SetInitializer() call from the Main() method and run the application again. You will find that the application picks up the database initializer details from the configuration file and creates the database as per the logic specified therein.


Database initialization in Code First refers to creating database and tables based on a model. Code First provides three inbuilt database initializers, viz. CreateDatabaseIfNotExists, DropCreateDatabaseWhenModelChanges and DropCreateDatabaseAlways. You can also create your own database initializer either by inheriting from existing initializers or by implementing the IDatabaseInitializer interface. The SetInitializer() method allows you to specify a database initializer to use for your application. In case your application needs to seed data you can override the Seed() method of the initializer class.

About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles



  • Thank you!

    Posted by That one fool on 03/29/2017 03:14pm

    I've spent over 4 hours trying to figure out how to make the Seed initializer work in my own project (with a different context and initializer, not the one in this example). The trick with putting this one line into the Global.asax file solved it: Database.SetInitializer(new BlogContextSeedInitializer());

  • typo: DropCreateDatabaseWhenModelChanges is in fact DropCreateDatabaseIfModelChanges

    Posted by Yours Tester on 04/27/2015 11:17am

    Well done. Pretty Good Overview. One small typo: DropCreateDatabaseWhenModelChanges is in fact DropCreateDatabaseIfModelChanges References: DropCreateDatabaseIfModelChanges Class https://msdn.microsoft.com/en-us/library/gg679604(v=vs.113).aspx

  • Code first not working

    Posted by RamkumarR on 03/26/2015 09:44pm

    Hi friends , i develop the code first approach in that i already created the DB and also i set my set initialize as null even though that was not working in a save changes place it shows error "Db update exception " kindly if know about this let me know . thanks

  • Query

    Posted by An on 08/13/2014 12:26am

    Database is created using code first . We have sqkl query fetching data from some table named "ëmployee" .but later on table name was changed to emp using migrations ,then errior is thrown in sql query , coz model has cjange . how to avoid such error

  • GOOD

    Posted by swapnil on 08/10/2014 10:27pm


  • developer

    Posted by Sharad Vishwakarma on 01/06/2014 03:41am

    where is Table attribute available in above class only because of this I'm not able to compile code . Please help me Waiting for positive reply

    • Table attribute

      Posted by porkncheese on 02/05/2014 01:17pm

      TableAttribute is in the System.ComponentModel.DataAnnotations.Schema namespace.

  • Changes to database without deleting existing data from Model in EF

    Posted by ramachandra on 02/28/2013 12:22pm

    In Entity Framework without deleting already exists records in database, how to make any changes in model to database

    • Re: Changes to database without deleting existing data from Model in EF

      Posted by Dio on 03/01/2013 03:47am

      Use migrations. It is very useful thing.

  • Oracle?

    Posted by Alejandro on 02/08/2013 12:05pm

    I am having the following error trying to run an Initializer with Oracle 11g express... any idea? DeleteDatabase is not supported by the provider. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.ProviderIncompatibleException: DeleteDatabase is not supported by the provider.

  • Why you created this blog?

    Posted by Zeeshan on 11/07/2012 09:00am

    Why do you create a blog when you don't bother to interact with any comments over here? Readers keep asking questions and you flee away. Get a static HTML website dude, or else disable the comments

  • Is there a defect?

    Posted by Daryn on 10/25/2012 05:54am

    Hi, Thanks for the post, specially the confog bit. There seems to be a bug in the 'Creating a Custom Database Initializer' section. There is no, if else, so you create a new database even if one exists. Is that correct?

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date