Click here to Skip to main content
12,445,931 members (74,092 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

34.6K views
15 bookmarked
Posted

Code First Migration in Multiple DbContext

, 28 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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 &ndash;ContextTypeName:ConsoleApp.EmployeeContext 
&ndash;MigrationDirectory:EmployeeContextMigrations 

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

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 &ndash;configuration Console.App.EmployeeContextMigrations.Configuration &ldquo;migration name&rdquo; 

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.

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

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

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.

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

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)

Share

About the Author

Sourav Kayal
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/

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionwhat is this command Pin
Rehan Mehdi13-Jan-16 1:56
memberRehan Mehdi13-Jan-16 1:56 
QuestionGetting error with foreign key reference to other db context Pin
Anoop X21-Jul-15 22:39
memberAnoop X21-Jul-15 22:39 
QuestionUseless copy/paste Pin
tbayart14-May-15 9:51
membertbayart14-May-15 9:51 
GeneralRe: Useless copy/paste Pin
antidemon13-Nov-15 1:47
memberantidemon13-Nov-15 1:47 
Questionwhere is source project?? :(( Pin
aminghaderi30-Mar-15 18:56
memberaminghaderi30-Mar-15 18:56 
QuestionCode First Migration in Multiple DbContext with common Entity Model Pin
kingley8-Nov-14 1:39
memberkingley8-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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160811.3 | Last Updated 28 Jul 2014
Article Copyright 2014 by Sourav Kayal
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid