Thursday, June 18, 2015

Entity Framework 6 Code First Migrations with Multiple Data Contexts

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

  1. public class User
  2. {
  3. public int UserID { set; get; }
  4. public string FirstName { set; get; }
  5. public string LastName { set; get; }
  6. }
  7.  
  8. public class Role
  9. {
  10. public int RoleID { set; get; }
  11. public string RolesName { set; get; }
  12. }
  13.  
  14. public class Order
  15. {
  16. public int OrderID { set; get; }
  17. public int Quantity { set; get; }
  18. public double Amount { set; get; }
  19. public DateTime Date { set; get; }
  20. }

DbContexts

  1. //first DbContext
  2. namespace MultiDataContextMigrations.Models
  3. {
  4. public class DataContext : DbContext
  5. {
  6. public DataContext()
  7. : base("DefaultConnection")
  8. {
  9.  
  10. }
  11.  
  12. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  13. {
  14. //TODO:Define mapping
  15. }
  16.  
  17. public DbSet Users { get; set; }
  18. public DbSet Orders { get; set; }
  19. }
  20. }
  21. //second DbContext
  22. namespace MultiDataContextMigrations.Models
  23. {
  24. public class UserDataContext : DbContext
  25. {
  26. public UserDataContext():base("DefaultConnection")
  27. {
  28. }
  29. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  30. {
  31. //TODO:Define mapping
  32. }
  33. public DbSet Users { get; set; }
  34. public DbSet Roles { get; set; }
  35. }
  36. }

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

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

Migrating First DbContext(DataContext)

  1. enable-migrations -ContextTypeName MultiDataContextMigrations.Models.DataContext -MigrationsDirectory:DataContextMigrations
  2. Add-Migration -configuration MultiDataContextMigrations.DataContextMigrations.Configuration Initial
  3. 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.
    1. internal sealed class Configuration : DbMigrationsConfiguration
    2. {
    3. public Configuration()
    4. {
    5. AutomaticMigrationsEnabled = false;
    6. //Helps to migrate this DbContext to database
    7. MigrationsDirectory = @"DataContextMigrations";
    8. }
    9. protected override void Seed(MultiDataContextMigrations.Models.DataContext context)
    10. {
    11. // This method will be called after migrating to the latest version.
    12. }
    13. }
  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:
    1. public partial class Initial : DbMigration
    2. {
    3. public override void Up()
    4. {
    5. CreateTable(
    6. "dbo.Orders",
    7. c => new
    8. {
    9. OrderID = c.Int(nullable: false, identity: true),
    10. Quantity = c.Int(nullable: false),
    11. Amount = c.Double(nullable: false),
    12. Date = c.DateTime(nullable: false),
    13. })
    14. .PrimaryKey(t => t.OrderID);
    15. CreateTable(
    16. "dbo.Users",
    17. c => new
    18. {
    19. UserID = c.Int(nullable: false, identity: true),
    20. FirstName = c.String(),
    21. LastName = c.String(),
    22. })
    23. .PrimaryKey(t => t.UserID);
    24. }
    25. public override void Down()
    26. {
    27. DropTable("dbo.Users");
    28. DropTable("dbo.Orders");
    29. }
    30. }
  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)

  1. enable-migrations -ContextTypeName MultiDataContextMigrations.Models.UserDataContext -MigrationsDirectory:UserDataContextMigrations
  2. Add-Migration -configuration MultiDataContextMigrations.UserDataContextMigrations.Configuration Initial
  3. 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.
    1. internal sealed class Configuration : DbMigrationsConfiguration
    2. {
    3. public Configuration()
    4. {
    5. AutomaticMigrationsEnabled = false;
    6. //Helps to migrate this DbContext to database
    7. MigrationsDirectory = @"UserDataContextMigrations";
    8. }
    9. protected override void Seed(MultiDataContextMigrations.Models.UserDataContext context)
    10. {
    11. // This method will be called after migrating to the latest version.
    12. }
    13. }
  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:
    1. public partial class Initial : DbMigration
    2. {
    3. public override void Up()
    4. {
    5. CreateTable(
    6. "dbo.Roles",
    7. c => new
    8. {
    9. RoleID = c.Int(nullable: false, identity: true),
    10. RolesName = c.String(),
    11. })
    12. .PrimaryKey(t => t.RoleID);
    13. CreateTable(
    14. "dbo.Users",
    15. c => new
    16. {
    17. UserID = c.Int(nullable: false, identity: true),
    18. FirstName = c.String(),
    19. LastName = c.String(),
    20. })
    21. .PrimaryKey(t => t.UserID);
    22. }
    23. public override void Down()
    24. {
    25. DropTable("dbo.Users");
    26. DropTable("dbo.Roles");
    27. }
    28. }
  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.
    1. public partial class Initial : DbMigration
    2. {
    3. public override void Up()
    4. {
    5. CreateTable(
    6. "dbo.Roles",
    7. c => new
    8. {
    9. RoleID = c.Int(nullable: false, identity: true),
    10. RolesName = c.String(),
    11. })
    12. .PrimaryKey(t => t.RoleID);
    13. //CreateTable(
    14. // "dbo.Users",
    15. // c => new
    16. // {
    17. // UserID = c.Int(nullable: false, identity: true),
    18. // FirstName = c.String(),
    19. // LastName = c.String(),
    20. // })
    21. // .PrimaryKey(t => t.UserID);
    22. }
    23. public override void Down()
    24. {
    25. DropTable("dbo.Users");
    26. DropTable("dbo.Roles");
    27. }
    28. }
    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.
  1. Update-Database -configuration MultiDataContextMigrations.DataContextMigrations.Configuration -TargetMigration:"201402141616393_Initial" -verbose
  2. 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

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

Migrating First DbContext(DataContext)

  1. //migrating DataContext
  2. enable-migrations -ProjectName:DAL -MigrationsDirectory:DataContextMigrations
  3. add-migration InitialCreate -ProjectName:DAL
  4. update-database -ProjectName:DAL -verbose

Migrating Second DbContext(UserDataContext)

  1. //migrating UserDataContext
  2. enable-migrations -ProjectName:MultiDataContextMigrations -MigrationsDirectory:UserDataContextMigrations
  3. add-migration InitialCreate -ProjectName:MultiDataContextMigrations
  4. 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.
  1. update-database -ProjectName:DAL -TargetMigration:"201401290826231_InitialCreate" -verbose
  2. 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.

No comments:

Post a Comment