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
Updated On : 23 Nov 2016
Total Views : 67,184   
Support : EF6
 

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...

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
11 DEC
ASP.NET MVC with AngularJS Development (offline)

Sat-Sun 09:30 AM-11:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri     6:30 AM-7:30 AM IST

3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (11:00 AM-12:30 PM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+