Entity Framework 6 Code First Migrations with Multiple Data Contexts

Entity Framework 6 Code First Migrations with Multiple Data Contexts

05 Apr 2024
Advanced
144K Views
7 min read
Learn with an interactive course and practical hands-on labs

Self-Paced ASP.NET Core Course

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.

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.

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:

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

    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.
     }
    }
    
  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.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");
     }
    }
    
  3. Thirdly, a new database will be created having initial catalog name (initial catalog = YourDBName) as given in your connections string.

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.

    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

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

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 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
What do you think?

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.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this