Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework code first migrations for two different databases

Tags:

I am quite confused with a situation here. I need to connect to two separate databases, one is a SQL Server database and the other is a MySQL database.

I have the connection strings in the web.config file. I am able to connect to the servers and access data.

But, I need to run entity migration on both the servers simultaneously. Or one by one, which I don't think is possible.

Here is my database context:

// Database 1
public class DatabaseContext : DbContext
{
    public DatabaseContext() : base("name=OldDBContext"){ }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) { }

    public static DatabaseContext Create()
    {
        return new DatabaseContext();
    }

    public DbSet<User> UserModel { get; set; }
}

// Database 2
public class NewDatabaseContext : DbContext
{
    public NewDatabaseContext() : base("name=NewDBContext") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) { }

    public static NewDatabaseContext Create()
    {
        return new NewDatabaseContext();
    }

    public DbSet<UserData> UserDataModel { get; set; }
}

Initially I had only one database and I used to run add-migration MigrationName in the package manager console and it would create a migration with the changes in the database.

But now, when I have two separate databases, the migrations does not contain any changes in the second database or the one I added later.

Please help. Any help is greatly appreciated.

Thank you

like image 245
Prashanth Benny Avatar asked Jul 22 '17 06:07

Prashanth Benny


1 Answers

Try to enable migrations for second context, use ContextTypeName parameter

Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
NamespaceOfContext.NewDatabaseContext 

It will create separate configuration. If naming conflicts occured rename configuration file in Migrations folder, then you can run database update for specific configuration

Update-Database -ConfigurationTypeName ConfigurationName
like image 167
Yusupov Avatar answered Sep 30 '22 01:09

Yusupov