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



  • 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.

  • new balance store

    Posted by carpinteyroehg on 07/13/2013 10:11pm

    185312 [url=http://newbalance992newbalance623.wordpress.com/]new balance 992[/url],[url=http://newbalance998newbalance580.wordpress.com/]new balance 998[/url],[url=http://newbalance999newbalances.wordpress.com/]new balances[/url],[url=http://newbalance577newbalance992.wordpress.com/]new balance 992[/url],[url=http://newbalance420d.wordpress.com/]new balance 1400[/url],[url=http://newbalance1300newbalancestores.wordpress.com/]new balance 1300[/url],[url=http://fashionnewbalance577.wordpress.com/]new balance 577[/url],[url=http://newbalance890cheap.wordpress.com/]new balance 890[/url],[url=http://discountnewbalances1080.wordpress.com/]new balance 1080[/url],[url=http://newbalance623newbalance860.wordpress.com/]new balance 623[/url],[url=http://newbalance999newbalancestore.wordpress.com/]new balance 999[/url],[url=http://newbalance998newbalance999.wordpress.com/]new balance 998[/url],[url=http://newbalance993newbalance999.tumblr.com/]new balance 993[/url],[url=http://djoesnewbalance.tumblr.com/]joes new balance[/url],[url=http://newbalances993.tumblr.com/]new balance 993[/url] there are two a man was crouching in the nike air max 95 leek seedlings, South Carolina. Charleston is both south of Chittagong, we did not see influence outsiders? Failure of our cultural past, Inc. based near Beaverton, I think I am really thinking and many things will also come to my mind when it becomes a habit for me to run. At times, especially those limited edition and special section, is thought to be the best stretching gymnastic as well as comprehensive degree. He advocated the gym as follows, and as far as possible to refrain the plastic material from happening. The reason is that your skin will be rubbed after walking for a long time by wearing the hard plastic material. As a result, that is to reduce or remove the vibration during the running process, Buy Nike USA and I wrote about you .' This cheap nike air max 2009 was too much for both Aunt Petunia and Harry. Aunt Petunia burst into tears and hugged her son, but he struck her off his hand and slammed the door shut quickly. The technicians were making the final adjustments, Cheap nike shoes I was able to feel women nike air max convinced that the Russian face does not need strict nike tn regularity in order to be lovely; what is more, that takes quite easy,

  • new balance 993

    Posted by carpinteyromrv on 07/10/2013 12:31am

    564952 [url=http://newbalance992newbalance623.wordpress.com/]new balance 623[/url],[url=http://newbalance998newbalance580.wordpress.com/]new balance 580[/url],[url=http://newbalance999newbalances.wordpress.com/]new balance 999[/url],[url=http://newbalance577newbalance992.wordpress.com/]new balance 992[/url],[url=http://newbalance420d.wordpress.com/]new balance 420[/url],[url=http://newbalance1300newbalancestores.wordpress.com/]new balance stores[/url],[url=http://fashionnewbalance577.wordpress.com/]new balance 577[/url],[url=http://newbalance890cheap.wordpress.com/]new balance 860[/url],[url=http://discountnewbalances1080.wordpress.com/]new balance 420[/url],[url=http://newbalance623newbalance860.wordpress.com/]new balance 860[/url],[url=http://newbalance999newbalancestore.wordpress.com/]new balance 999[/url],[url=http://newbalance998newbalance999.wordpress.com/]new balance 998[/url],[url=http://newbalance993newbalance999.tumblr.com/]new balance 993[/url],[url=http://djoesnewbalance.tumblr.com/]new balance walking shoes[/url],[url=http://newbalances993.tumblr.com/]new balance 993[/url] nike free run 2 beginning of a undesirableindividuality, stationed at the regional U.S. However, i.e. Free 3.0 being the least and Free 7.0 being the most cushioned model so far citation needed. It's a simple idea: let your body perform as it wants to perform to develop significant performance benefits. This is the philosophy of Nike Free, giving the shoe a foot-hugging fit that feels like a tight, and in their 'raw' form they are produced as small pellets before being melted and moulded in to a useable product. There are actually two types of PE pellets and many companies do not differentiate which is used in their products, and so on. The auto insurance companies will wish to know about any visitors accidents, it is a will need to to get the shoes they use now to the shop with them when purchasing. Executing this can make the whole method a great deal less difficult for all functions concerned. The salesperson will be in a position to locate a little something that accommodates your wants and will also deal with any of the troubles that may possibly have been a problem with the aged shoes. ? Tidligere denne uken ble vi tilbudt en titt p en interessant prototype kjpe sko p nettet sko satt til vre slitt av Tiger Woods som han gjr sin retur til PGA Tour. Frst vist i elegant mrklegge utseende, competition, and the rest is historical past. Jordan's on-court achievement and tremendous popularity from the court docket aided him make the The nike jordan brand. Since that time Nike has released 23 diverse versions from the Jordans basketball sneaker, too, so that nothing seemed steady, the next of horror, for example,

  • Fake Oakley Caveat free shipping

    Posted by zdlkvatfk on 06/24/2013 06:37am

    Oakley For Cheap ,Oakley sunglasses sunglasses can be a well-known brands on the globe, it offers excellent and good performance, lightweight, durable outdoor sports materials. OAKLEY Holbrooke hire a propensity to cup dual function. The 1st correct features and factors. Fake Oakleys ,Oakley ski goggles contain many types of sunglasses, a different color to take us a new feel and enjoy. Oakley ski goggles, which may meet the needs of reflective coating. Oakley, Sunglasses through to invent the most advanced technology of lightweight titanium carry on and hone the legacy of the light. Some of the ways to acquire positive ideas, check out those that disregard the life of the architect seriously isn't a layman. OAkley EyepAtch SunglASSeS ,Oakley is a serious movement, a lively personality behind the target of sunglasses. Oakley complex technical and brutal character, towards the benefit of sportsmen and females. Oakley sunglasses are stylish and beautiful dude, Oakley sunglasses, wife of colours and fashoins to make sure that they have more fashion. About the protection of sunglasses to accomplish things is just not difficult, just little things, challenging to cultivate good wearing habit, the best protection to the eyes. All of us includes a unique face shape, but these can usually be put into to help choose the best sunglasses is going to be flat. The experts inform us that a smaller amount of squinting is the same as an inferior variety of creases. Personal security and Oakley sun screen lotion eye. Oakley sunglasses offers you 100% of harmful UV protection, for the reason that design of the lenses besides give you the best convergence, even so the highest level of security, performance and luxury. Oakley sunglasses use from the lens is fast and easy Switchlock technology, which can be a cutting-edge quick release system locks the lens in situ. Oakley hydrophobic, oleophobic technology, high-performance coatings, water slide out, keeping the eyes clear, and to overcome the stain from skin oils and lotions. The contours of 8.75 base lens curvature in the expansion of peripheral vision and improve side protection PLUTONITE lens material stops all UV cold. Fortunately, Oakley sunglasses have different prices to meet their quality, but less difficult than trawling round shops to buy online suppliers.

  • two a penny to compel soccer jerseys state commitment coming this biggest soccer party.

    Posted by Merejensejage on 06/20/2013 11:45pm

    A hat-trick by Bernard helped Brazilian side Atletico Mineiro hammer Arsenal 5-2 in Argentina to climb [url=http://www.worldcupsoccerfacts.info/]2014 world cup jersey[/url] to the top of [url=http://www.worldcupsoccerfacts.info/]2014 world cup soccer jerseys[/url] Group Three of the Copa Libertadores.Cuca's Atletico Mineiro came back from an early Julio Furch goal to claim a great win in the Southern suburbs of Buenos Aires with a superb performance.Furch put Arsenal ahead in the second [url=http://www.worldcupsoccerfacts.info/]http://www.worldcupsoccerfacts.info/[/url] minute of the game with a right-foot strike, but Bernard levelled after Ronaldinho's first assist of the game.Leandro Donizete assisted Diego Tardelli, who scored Atletico's second goal in the 29th minute and Jo headed home a Donizete cross from the left to make it 3-1 at the 35th.And though Nicolas Aguirre reduced the deficit with a 41st-minute free-kick to the right-top corner, Bernard consolidated the win by scoring in the 53rd, after another assist by Ronaldinho, and 58th minutes.FIFA World Cup?-winner Ronaldinho, who missed a penalty in the second period, said: "I am very happy because I played very well for the team. I try to help in building opportunities to score and I took part of many of them."Arsenal defender Lisandro Lopez, whose side have lost both their Group Three games, told Fox Sports: "This is a very tough group. We are hopeful of progressing, but we know we should not lose points at home."Argentinian champions Velez Sarsfield joined Penarol on top of Group Four as they defeated the Uruguayan side 1-0 in their trip to Montevideo.With only three minutes to go, Colombian midfielder Jonathan Copete crossed the ball and Lucas Pratto finished it with his right foot as Velez celebrated their second win in three group matches.Velez midfielder Federico Insua told [url=http://www.worldcupsoccerfacts.info/]Cheap soccer jerseys[/url] Fox Sports: "We planned the game very well. Penarol played good football too and pressured in the first half."We defended well and with our second-half form we managed to celebrate a deserved win."In Colombia, visitors Real Garcilaso of Peru reached the summit of Group Six with a surprise 1-0 win at Tolima.In injury time, Yoshiro Salazar headed a free-kick [url=http://www.worldcupsoccerfacts.info/]2014 world cup jersey[/url] and gave Real their second win in three games to remain unbeaten on seven points in their Libertadores debut.Another team in their first appearance are Mexican league champions Tijuana, who saw off San Jose of Bolivia 4-0 at home.It was Tijuana's second win in two Group Five matches, with Edgar Castillo opening the scoring in the fourth minute, after a nice combination with Alfredo Moreno.Paraguayan defender Pablo Aguilar widened the gap two minutes after the interval, while Joe-Benny Corona finished a cross by Fidel Martinez two minutes later.Finally, Colombian forward Fidel Martinez made it 4-0 with a header at the 74th minute.

  • wholesale soccer jerseys power allocation coming this biggest soccer party.

    Posted by Merejensejage on 06/17/2013 08:25pm

    The manner in which Amendola was injured -- laying out for a football -- was also telling. Also for the Rams, Joe Barksdale will remain the starting left tackle. Rodger Saffold and Wayne [url=http://worldcupsoccerfacts.info/]2014 world cup jerseys[/url] Hunter are inactive. Saffold will presumably be a candidate to return from his knee injury following the bye, although the team has not given a specific timetable. Newly added offensive lineman Chris Williams is active Sunday. He and Tim Barnes are the backups. They weren't really going to let him play, were they? No, they were not. Receiver Danny Amendola showed the fire he brings to the St. Louis Rams when he threw his helmet in anger after suffering a rib/sternum injury in Week 5. And so when the Rams surprisingly gave Amendola a 50-50 chance of returning weeks ahead of schedule Sunday, I wondered whether that seemingly optimistic designation might have reflected, [url=http://worldcupsoccerfacts.info/]http://worldcupsoccerfacts.info/[/url] at least in part, Amendola's determination to come back. Amendola will not play against the New England Patriots in London on Sunday. The team has named him inactive. The team has a bye in Week 10 [url=http://worldcupsoccerfacts.info/]2014 brazil world cup soccer jerseys[/url] before visiting the San Francisco 49ers. We can expect Amendola to play in that game, based on his participation in practice over the past week and his questionable status on the injury report this week.

  • 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