Please enable Javascript to correctly display the contents on Dot Net Tricks!

Entity Framework 6 Code First Migrations with Multiple Data Contexts

  Author : Shailendra Chauhan
Posted On : 14 Feb 2014
Total Views : 76,488   
Updated On : 23 Nov 2016
 

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.



ABOUT AUTHOR

Shailendra Chauhan
Author, Architect, Corporate Trainer and Microsoft MVP

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers, ASP.NET MVC Interview Questions and Answers, AngularJS Interview Questions and Answers and LINQ Interview Questions and AnswersKnow more...

Free Interview Books
 
COMMENTS (3)
Dustin Nulf Reply

This is great help, Mr. Chauhan. I'm using multiple dbContexts in my webforms app. Consider this scenario: I have a development database and a production "live" database. Right now, I can successfully manage the migrations, database, and code with the development database. Now it's time to update the production database. How do I roll the changes into the production database, without losing data, and getting everything sync'd? Thanks for any insight! -Dustin

Jnet Reply

What if entities there some relationship with the entities? like Order is related to User by userid. Whether we need to explicitly define these relation somewhere?

Mara Reply

Good Article.Thanks

23 MAY
Xamarin Forms : Build Cross-platform Apps (Online)

09:00 PM-11:00 PM IST(+5.30 GMT)

Know More
5 MAY
ASP.NET MVC with Angular4 Development (Online)

06:30 AM-08:30 AM IST(+5.30 GMT)

Know More
29 APR
Xamarin Forms : Build Cross-platform Apps (Classroom)

5:00 PM-6:30 PM

Know More
29 APR
ASP.NET MVC with Angular2 Development (Classroom)

9:30 AM-11:00 AM

Know More
27 APR
ASP.NET Core Development (Online)

07:00 AM - 09:00 AM IST( TUS, THR)

Know More
22 APR
NodeJS Development (Classroom)

11:00 AM-12:30 PM

10 APR
Master Class ASP.NET MVC 5 with Angular2 Plus Angular4 Development (Online)

09:00 PM - 11:00 PM IST (M/W/F)

8 APR
MEAN Stack 2 Development (Classroom)

11:00 AM-12:30 PM

25 MAR
Xamarin Forms : Build Cross-platform Apps (Classroom)

8:00 AM-9:30AM

21 MAR
ASP.NET MVC with Angular2 Development (Online)

09:00 PM - 11:00 PM IST( TUS, THR, SAT)

25 FEB
ASP.NET MVC with Angular2 Development (Classroom)

03:30 PM-05:30 PM

24 FEB
Angular 2 with Type Script (Online)

09:00 PM-11:00 PM IST(Mon,Wed,Fri)

BROWSE BY CATEGORY
 
 
LIKE US ON FACEBOOK
 
+