Code First database migration in Entity Framework

 06-Apr-2014   nityaprakash     EntityFramework    Comments  0

This post explains how to do code first database migration works with Entity Framework. I like to work. There are some time require to group some set of entities and want to migrate separately. For example, I usually group User related tables in one DbContext and other tables in different context unless they are not tightly related. In this case, there should be two migration folders within migration folder in my application. If there is multiple DataContext in our application, than there must be separate migration folder for each DataContext.

For Example below is my DbContext and DbSet classes:


    class InventoryContext :DbContext
        public InventoryContext()
            : base("DbConnection")
        public DbSet UserProfile { get; set; }

DbSet Class

    class UserProfile
        public int UserId { get; set; }
        public string UserName { get; set; }
        public DateTime DateOfBirth { get; set; }

There are following steps are involved for migration:

  • Enable Migration
  • Add Migration
  • Update Database
EF6.0 allows to create multiple migration folders within Migration folder.

Enable Migration

Open Package Manager Console from View->Other Windows and run following command.

PM>Enable-Migrations -ContextTypeName WPFDemo.InventoryContext -MigrationsDirectory:Migrations\Inventory

Note: In Package Manager console window it Default project should always be the project where entities are defined and migration need to be added.

This command will create Inventory folder inside Migrations folder.

this statement will generate following Configuration File:

namespace WPFDemo.Migrations.Inventory
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    internal sealed class Configuration : DbMigrationsConfiguration
        public Configuration()
            AutomaticMigrationsEnabled = false;
            MigrationsDirectory = @"Migrations\Inventory";
       protected override void Seed(WPFDemo.InventoryContext context)

Seed method created in this class will allow you to insert or update initial data in DBContext. This will be executed in the last step when we finally update the schema of connected database.

This step is first time setup. Once folder is created, we just have to Add Migration on each update.

Add Migration

Now we need to add migration in Migration folder when any schema changes or DBContext classes changes happen. PM> Add-Migration -ConfigurationType WPFDemo.Migrations.Inventory.Configuration "InitialSetup" This command generates a class in Migration folder with prefix provided in above command. In this case it is "InitialSetup", it is your choice.

 public partial class InitialSetup : DbMigration
        public override void Up()
                c => new
                        UserId = c.Int(nullable: false, identity: true),
                        UserName = c.String(maxLength: 50),
                        DateOfBirth = c.DateTime(nullable: false),
                .PrimaryKey(t => t.UserId);
        public override void Down()

Update Database

Last step is to apply changes in Database by running Update-Database command.

PM> update-database -ConfigurationType WPFDemo.Migrations.Inventory.Configuration

This command to apply database changes for specific configuration. If we run command without any parameter, it'll run changes for all migration. Class is derived from DbMigration class, which is overriding two methods: * Up(): This method is executed for Upgrade process. * Down(): This method is executed for Downgrade process when we want to revert the database changes.

Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment