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
{
    [TestClass]
    public class BookContextTests
    {
        [TestMethod]
        public void SetCodeFirstMigrationsInitializerTest()
        {
            Database.SetInitializer(
                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"
                        };
 
                context.Books.Add(book);
                context.SaveChanges();
            }
        }
    }
}

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:

<contexts>
  <context type="Custom DbContext name, Assembly name">
    <databaseInitializer
      type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[
        Custom DbContext name, Assembly name], 
        [Configuration class name, Assembly name]], 
        EntityFramework" />
  </context>
</contexts>

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"?>
 
<configuration>
  <configSections>
    <section name="entityFramework"
             type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, 
             EntityFramework, Version=4.3.1.0, Culture=neutral, 
             PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory 
      type="System.Data.Entity.Infrastructure.SqlConnectionFactory, 
        EntityFramework">
      <parameters>
        <parameter 
          value="Data Source=.\SQLEXPRESS; Integrated Security=True; 
            MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
    <contexts>
      <context 
        type="EntityFrameworkDemo.BookContext, EntityFrameworkDemo">
        <databaseInitializer 
          type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[
            EntityFrameworkDemo.BookContext, EntityFrameworkDemo], 
            [EntityFrameworkDemo.Migrations.Configuration, EntityFrameworkDemo]], 
            EntityFramework" />
      </context>
    </contexts>
  </entityFramework>
</configuration>
 

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.

4 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?