Entity Framework Code First Migrations Database Initializer

In the previous example we enabled Entity Framework Code First Migrations and upgraded the database manually each time if needed. It’s also possible to make this happen automatically, either directly in code or by configuration. We just need to specify the correct database initializer strategy.

Initialization in Code

We specify our database initializer strategy in code with a call to the Database.SetInitializer method passing the MigrateDatabaseToLatestVersion strategy for our custom DbContext and the Configuration class. This is the class created when we first enabled Code First Migrations. Now this Configuration class has the internal sealed access modifiers by default, so we can’t access nor inherit from it as a client. In order to use it in our code we need to change it to being a public class.

using System.Data.Entity.Migrations;
namespace EntityFrameworkDemo.Migrations
    //internal sealed by default
    public class Configuration : DbMigrationsConfiguration<BookContext>
        public Configuration()
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        protected override void Seed(BookContext context)

Now we only need to call Database.SetInitializer with the MigrateDatabaseToLatestVersion strategy before we create our custom DbContext and we’re set. Each time we change something in our Code First model those changes are automatically reflected in the database.

using System;
using System.Data.Entity;
using EntityFrameworkDemo;
using EntityFrameworkDemo.Migrations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EntityFrameworkDemoTests
    public class BookContextTests
        public void SetCodeFirstMigrationsInitializerTest()
                new MigrateDatabaseToLatestVersion<BookContext, Configuration>());
            using (var context = new BookContext())
                var author =
                    new Author
                            Name = "Leon van Bokhorst",
                            Birthday = new DateTime(2020, 1, 12),
                var book =
                    new Book
                            Author = author,
                            Excerpt = "Nice book",
                            PublishDate = DateTime.Today,
                            Title = "My little book"

Initialization by Configuration

Another, more convenient way, is to specify our database initializer within our App.config. We don’t have to change the Configuration class access modifier from the internal sealed default. In the entityFramework section of our App.config we add our context and its database initializer type. Pseudo syntax looks something like this:

  <context type="Custom DbContext name, Assembly name">
        Custom DbContext name, Assembly name], 
        [Configuration class name, Assembly name]], 
        EntityFramework" />

We need to provide our fully qualified custom DbContext class name, Configuration class and Assembly name. Here’s the App.config for the Code First Migrations BookContext database initializer.

<?xml version="1.0" encoding="utf-8"?>
    <section name="entityFramework"
             EntityFramework, Version=, Culture=neutral, 
             PublicKeyToken=b77a5c561934e089" />
          value="Data Source=.\SQLEXPRESS; Integrated Security=True; 
            MultipleActiveResultSets=True" />
        type="EntityFrameworkDemo.BookContext, EntityFrameworkDemo">
            EntityFrameworkDemo.BookContext, EntityFrameworkDemo], 
            [EntityFrameworkDemo.Migrations.Configuration, EntityFrameworkDemo]], 
            EntityFramework" />

Rather ugly but convenient. Again each time our DbContext is created it loads the specified database initializer strategy. More information on Entity Framework 4.3 Configuration File Settings on the ADO.NET weblog.

5 thoughts on “Entity Framework Code First Migrations Database Initializer

  1. You need to update the Configuration class in the first code listing. You are now supposed to derive it from System.Data.Entity. Migrations.DbMigrationsConfiguration rather than say DbMigrations. Darn Microsoft, always refactoring their libraries!

    • i also not automatically migration .
      i try to automatically migration asp.net identity security but I did not succeed!
      after a lot of research , i understanding this work not possible in initial framework.
      tnx Leon.

  2. Hey Brain,

    As far as I can see the Configuration class in the first listing does derive from System.Data.Entity. Migrations.DbMigrationsConfiguration.

    Am I missing your point?

  3. Great article thanks! I’m getting an error on one of my objects. I have a table already created in my db called Vendor. When i run my code, it tells me there’s already an object named ‘Vendor’ in the db. Yes, this i know! :) But i thought it was supposed to update the vendor table. Am i missing something?

  4. Thank you so much. I have been struggling all day on getting this to work. I read so many articles, blog posts, and stack overflow questions that seemed to be attempting the same thing in different ways. This is the only thing that has worked for me and it works perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>