Entity Framework 6 Code First Migrations with Multiple Data Contexts

Entity Framework 6 Code First Migrations with Multiple Data Contexts

29 Aug 2025
Advanced
147K Views
9 min read
Learn with an interactive course and practical hands-on labs

Free ASP.NET Core Online Course with Certificate - Start Now

Entity Framework code first migrations allows you to create a new database or to update existing database based on your model classes. Entity Framework5 code first migrations is only able to manage a single DbContext per physical database instance. Now, Entity Framework6 code first migrations is able to manage multiple DbContext per physical database instance. Let's see how to make it possible using EF6.

Suppose you have two DbContexts DataContext and UserDataContext. You need to migrates these two into single database instance. In this Entity Framework Tutorial, we will see how 6 Code First Migrations done. Meanwhile if you are preparing for interview bookmark Top 50 Entity Framework Interview Questions & Answers for your further study. Now let's start.

Model Classes


public class User
{
 public int UserID { set; get; }
 public string FirstName { set; get; }
 public string LastName { set; get; }
}

public class Role
{
 public int RoleID { set; get; }
 public string RolesName { set; get; }
} 

public class Order
{
 public int OrderID { set; get; }
 public int Quantity { set; get; }
 public double Amount { set; get; }
 public DateTime Date { set; get; }
}

DbContexts


//first DbContext
namespace MultiDataContextMigrations.Models
{
public class DataContext : DbContext
{
 public DataContext()
 : base("DefaultConnection")
 {

 }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
 //TODO:Define mapping
 }

 public DbSet Users { get; set; }
 public DbSet Orders { get; set; }
}
}

//second DbContext
namespace MultiDataContextMigrations.Models
{
public class UserDataContext : DbContext
{
 public UserDataContext():base("DefaultConnection")
 {

 }
 
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
 //TODO:Define mapping
 }
 
 public DbSet Users { get; set; }
 public DbSet Roles { get; set; }
}
}

Case 1 : Multiple DbContexts within a Project

Suppose you have both DbContexts within a single project as shown in fig.

DBContext

For migrating these two DbContexts to single database instance run the following commands by using VS2013 or VS2012 package manager console as given below:

Syntax - EF Code First Migrations with Multiple DbContexts within same Project


enable-migrations -ContextTypeName <DbContext-Name-with-Namespaces> -MigrationsDirectory:<Migrations-Directory-Name>
Add-Migration -configuration <DbContext-Migrations-Configuration-Class-with-Namespaces> <Migrations-Name>
Update-Database -configuration <DbContext-Migrations-Configuration-Class-with-Namespaces> -Verbose

Migrating First DbContext(DataContext)


enable-migrations -ContextTypeName MultiDataContextMigrations.Models.DataContext -MigrationsDirectory:DataContextMigrations
Add-Migration -configuration MultiDataContextMigrations.DataContextMigrations.Configuration Initial
Update-Database -configuration MultiDataContextMigrations.DataContextMigrations.Configuration -Verbose

When you run above listed command on the Package Manager Console windows one by one then:

Firstly a Migrations folder will be added into your applications having Configuration.cs file for Migrations configuration setting.

Configuration.cs


internal sealed class Configuration : DbMigrationsConfiguration
{
 public Configuration()
 {
 AutomaticMigrationsEnabled = false;
 //Helps to migrate this DbContext to database
 MigrationsDirectory = @"DataContextMigrations"; 
 }

 protected override void Seed(MultiDataContextMigrations.Models.DataContext context)
 {
 // This method will be called after migrating to the latest version.
 }
}

Secondly a class file will be created having name suffix as MigrationsName followed by underscore and a unique generated number. This file will have all the entities to be created in the database as shown below:


public partial class Initial : DbMigration
{
 public override void Up()
 {
 CreateTable(
 "dbo.Orders",
 c => new
 {
 OrderID = c.Int(nullable: false, identity: true),
 Quantity = c.Int(nullable: false),
 Amount = c.Double(nullable: false),
 Date = c.DateTime(nullable: false),
 })
 .PrimaryKey(t => t.OrderID);
 
 CreateTable(
 "dbo.Users",
 c => new
 {
 UserID = c.Int(nullable: false, identity: true),
 FirstName = c.String(),
 LastName = c.String(),
 })
 .PrimaryKey(t => t.UserID);
 
 }
 
 public override void Down()
 {
 DropTable("dbo.Users");
 DropTable("dbo.Orders");
 }
}

Thirdly, a new database will be created having initial catalog name (initial catalog = YourDBName) as given in your connections string.

YourDBname

Migrating Second DbContext(DataContext)


enable-migrations -ContextTypeName MultiDataContextMigrations.Models.UserDataContext -MigrationsDirectory:UserDataContextMigrations
Add-Migration -configuration MultiDataContextMigrations.UserDataContextMigrations.Configuration Initial
Update-Database -configuration MultiDataContextMigrations.UserDataContextMigrations.Configuration -Verbose

When you run above listed command on the Package Manager Console windows one by one then:

  1. Firstly a Migrations folder will be added into your applications having Configuration.cs file for Migrations configuration setting.

    Configuration.cs
    
    internal sealed class Configuration : DbMigrationsConfiguration
    {
     public Configuration()
     {
     AutomaticMigrationsEnabled = false;
     //Helps to migrate this DbContext to database
     MigrationsDirectory = @"UserDataContextMigrations";
     }
    
     protected override void Seed(MultiDataContextMigrations.Models.UserDataContext context)
     {
     // This method will be called after migrating to the latest version.
     }
    }
    
  2. Secondly a class file will be created having name suffix as MigrationsName followed by underscore and a unique generated number. This file will have all the entities to be created in the database as shown below:

    
    public partial class Initial : DbMigration
    {
     public override void Up()
     {
     CreateTable(
     "dbo.Roles",
     c => new
     {
     RoleID = c.Int(nullable: false, identity: true),
     RolesName = c.String(),
     })
     .PrimaryKey(t => t.RoleID);
     
     CreateTable(
     "dbo.Users",
     c => new
     {
     UserID = c.Int(nullable: false, identity: true),
     FirstName = c.String(),
     LastName = c.String(),
     })
     .PrimaryKey(t => t.UserID);
     
     }
     
     public override void Down()
     {
     DropTable("dbo.Users");
     DropTable("dbo.Roles");
     }
    }
    
  3. Before running update command, commented out the generated code for Users tables as shown above. Since Users table is already created by first DbContext migrations.

    
    public partial class Initial : DbMigration
    {
     public override void Up()
     {
     CreateTable(
     "dbo.Roles",
     c => new
     {
     RoleID = c.Int(nullable: false, identity: true),
     RolesName = c.String(),
     })
     .PrimaryKey(t => t.RoleID);
     //CreateTable(
     // "dbo.Users",
     // c => new
     // {
     // UserID = c.Int(nullable: false, identity: true),
     // FirstName = c.String(),
     // LastName = c.String(),
     // })
     // .PrimaryKey(t => t.UserID);
     }
     public override void Down()
     {
     DropTable("dbo.Users");
     DropTable("dbo.Roles");
     }
    }
    

    Now, run the third command then it will update the already created database by first DbContext migrations.

__MigrationHistory table

migration history

This table will contain all the migrations changes to database. Let's have a look on this table. In this way, you have successfully migrated both DbContexts to same database within SQL Server.

Undo/Rollback DbContexts Migrations

You can also rollback database changes by running following set of commands for both the DbContexts.


Update-Database -configuration MultiDataContextMigrations.DataContextMigrations.Configuration -TargetMigration:"201402141616393_Initial" -verbose
Update-Database -configuration MultiDataContextMigrations.UserDataContextMigrations.Configuration -TargetMigration:"201402141641408_Initial" -verbose

Case 2 : Multiple DbContexts within different Projects

Multiple dbcontext

Suppose you have both DbContexts within different projects as shown in fig.

For migrating these two DbContexts to single database instance run the following commands by using VS2013 or VS2012 package manager console as given below:

Syntax - EF Code First Migrations with Multiple DbContexts within different Projects


enable-migrations -ProjectName:<ProjectName> -MigrationsDirectory:<Migrations-Directory-Name>
add-migration <Migrations-Name> -ProjectName:<ProjectName>
update-database -ProjectName:<ProjectName> -verbose

Migrating First DbContext(DataContext)

Migrating first dbcontext


//migrating DataContext
enable-migrations -ProjectName:DAL -MigrationsDirectory:DataContextMigrations
add-migration InitialCreate -ProjectName:DAL
update-database -ProjectName:DAL -verbose

Migrating Second DbContext(UserDataContext)


//migrating UserDataContext
enable-migrations -ProjectName:MultiDataContextMigrations -MigrationsDirectory:UserDataContextMigrations
add-migration InitialCreate -ProjectName:MultiDataContextMigrations
update-database -ProjectName:MultiDataContextMigrations -verbose

Undo/Rollback DbContexts Migrations

You can also rollback database changes by running following set of commands for both the DbContexts.


update-database -ProjectName:DAL -TargetMigration:"201401290826231_InitialCreate" -verbose
update-database -ProjectName:MultiDataContextMigrations -TargetMigration:"201401290836540_InitialCreate" -verbose
Conclusion

I hope you will enjoy the tips while programming with Entity Framework. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

FAQs

 By using the -MigrationsDirectory option, you can create separate folders for each context’s migration files, ensuring they don’t interfere with each other. 

 Yes, each DbContext should have its own Configuration class in its respective Migrations folder to handle migration settings like AutomaticMigrationsEnabled

Yes, but it is generally recommended to keep them separate to avoid conflicts. If they must share a database, carefully manage table mappings and migration configurations. 

Take our Entityframework skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

He is a renowned Speaker, Solution Architect, Mentor, and 10-time Microsoft MVP (2016–2025). With expertise in AI/ML, GenAI, System Design, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development, he bridges traditional frameworks with next-gen innovations.

He has trained 1 Lakh+ professionals across the globe, authored 45+ bestselling eBooks and 1000+ technical articles, and mentored 20+ free courses. As a corporate trainer for leading MNCs like IBM, Cognizant, and Dell, Shailendra continues to deliver world-class learning experiences through technology & AI.
Live Training - Book Free Demo
ASP.NET Core Certification Training
21 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this