5

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

Prashanth Benny
  • 1,523
  • 21
  • 33
  • How are you registering the two DbContexts in your Startup file? Also, are you wanting both databases to update when data is changed? – KidCode Jul 22 '17 at 07:02
  • @KidCode I have not registred any database in global.asax. when I had only one database, I guess it was not necessary. – Prashanth Benny Jul 22 '17 at 07:16
  • @KidCode I want to update the database schema like when I do `update-database` or `add-migration` but only one db is getting updated. – Prashanth Benny Jul 23 '17 at 07:23

1 Answers1

4

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
Yusupov
  • 382
  • 2
  • 11
  • 1
    Also check https://stackoverflow.com/questions/13469881/how-do-i-enable-ef-migrations-for-multiple-contexts-to-separate-databases question – Yusupov Jul 22 '17 at 07:38