Entity Framework code first migrations for two different databases

c# ef-code-first ef-migrations entity-framework entity-framework-6

Question

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

1
5
7/26/2017 2:07:52 AM

Accepted Answer

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
4
7/22/2017 7:33:28 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow