Click here to Skip to main content
15,895,656 members
Articles / Programming Languages / C#
Tip/Trick

Code First Migration in Multiple DbContext

Rate me:
Please Sign up or sign in to vote.
4.90/5 (16 votes)
28 Jul 2014CPOL2 min read 97.5K   25   7
In this tip, we will learn to migrate database when multiple DbContext is present in the same application.

Introduction

In our previous articles, we have seen various strategies to use Entity Framework in application. We have seen code first approach and how to handle inheritance? Database initialization strategy and various concepts. You can read those here:

In this tip, we will discuss how we can migrate changes into database when there are multiple DbContext classes. First point first” Entity Framework 6.0 and upper supports multiple DbContext class”. Those two context classes may belong from single database or two different databases no matter. In our example, we will define two Context classes for same database. So, let’s take one empty application, in my case, I have chosen Console application for demo. Have a look at the below code:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    [Table("Employee")]
    public class Employee
    {
        [Key]
        public int EmpId { get; set; }
        
        [Required]
        [MaxLength(20)]
        public string name { get; set; }

        [Required]
        [MaxLength(20)]
        public string surname { get; set; }
    }

    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("DBConnectionString") { }

        public DbSet<Employee> Employee { get; set; }
    }

    [Table("Customer")]
    public class Customer
    {
        [Key]
        public int CustomerId { get; set; }

        [Required]
        [MaxLength(20)]
        public string name { get; set; }

        [Required]
        [MaxLength(20)]
        public string surname { get; set; }
    }

    public class CustomerContext : DbContext
    {
        public CustomerContext() : base("DBConnectionString") { }

        public DbSet<Customer> Customer { get; set; }
    }
}

There are two models called “Employee” and “Customer”. Each one is associated with a particular corresponding context class, i.e., Employee is associated with EmployeeContext and Customer is associated with CustomerContext. Fine, now we will migrate the model in database individually for these two context classes. Here is the basic rule to migrate changes in database when there are multiple Context classes within the 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

This is very similar with migration of single Context model except for a few extra parameters. So, let’s open Package Manager Console of nuGet and write the below command.

 Enable-migration –ContextTypeName:ConsoleApp.EmployeeContext 
–MigrationDirectory:EmployeeContextMigrations 

Here, ConsoleApp is the namespace of EmployeeContext class. Here is the command in action.

Image 1

Once it is executed, we will add the model in migration history and for that, we have to fire add-migration command in same console. The command is something like below in my case.

 Add-migration –configuration Console.App.EmployeeContextMigrations.Configuration "migration name" 

Here, the parameter name is –configuration and it takes path of configuration class for this migration. The “Initial” is the migration name which may need to rollback any changes in database.

Image 2

If the command executes successfully in console, we will see that the migration folder has created for Employee model just like below screen.

Image 3

If we open the migration file, we will see that the migration code is automatically generated.

C#
namespace ConsoleApp.EmployeeContextMigrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Employee",
                c => new
                    {
                        EmpId = c.Int(nullable: false, identity: true),
                        name = c.String(nullable: false, maxLength: 20),
                        surname = c.String(nullable: false, maxLength: 20),
                    })
                .PrimaryKey(t => t.EmpId);
        }
        public override void Down()
        {
            DropTable("dbo.Employee");
        }
    }
}

In the same way, we can migrate the Customer model. Once finished, we should see the below screen in solution. Two separate folders should create for two different context classes.

Image 4

Once we open the database, we will see that two different tables are created for two different models.

Image 5

Border Line

In this tip, we have learned to migrate database when there are multiple DbContext classes in the same application. Please keep in mind that Entity Framework 6.0 onwards supports this feature. Multiple DbContext make sense if they represent two different databases, though in our example we have used single database for both contexts.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
GeneralMy vote of 5 Pin
ghader_h6-Aug-17 3:57
ghader_h6-Aug-17 3:57 
Questionwhat is this command Pin
Rehan Mehdi13-Jan-16 1:56
Rehan Mehdi13-Jan-16 1:56 
QuestionGetting error with foreign key reference to other db context Pin
Anoop X21-Jul-15 22:39
Anoop X21-Jul-15 22:39 
QuestionUseless copy/paste Pin
tbayart14-May-15 9:51
professionaltbayart14-May-15 9:51 
Nothing explained, just a partial copy/paste from a msdn article
https://msdn.microsoft.com/en-us/data/jj591621[^]
GeneralRe: Useless copy/paste Pin
antidemon13-Nov-15 1:47
antidemon13-Nov-15 1:47 
Questionwhere is source project?? :(( Pin
aminghaderi30-Mar-15 18:56
aminghaderi30-Mar-15 18:56 
QuestionCode First Migration in Multiple DbContext with common Entity Model Pin
kingley8-Nov-14 1:39
kingley8-Nov-14 1:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.