0
votes

So I'm trying to run the database update in MVC 5 within an MVC action:

public async Task<ActionResult> UpdateDatabase(UpdateDatabaseModel updateDatabaseModel)
{
    DbMigrationsConfiguration migrationsConfiguration = new DbMigrationsConfiguration
    {
        TargetDatabase = new DbConnectionInfo("DefaultConnection"),
        ContextType = typeof(ApplicationDbContext),
        MigrationsAssembly = typeof(ApplicationDbContext).Assembly
    };

    var migrator = new DbMigrator(migrationsConfiguration);
    migrator.Update(updateDatabaseModel.SelectedMigration);
    return this.View("ManageApplication");
 }

The problem is, at migrator.Update(updateDatabaseModel.SelectedMigration); it throws an error:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

But when I do an add-migration, the Up() and Down() are empty (also after adding this migration, it still throws that exception)

Any idea?

I also checked this one: EF Add-Migration indicates "No pending explicit migrations" but Update-Database complains "..there are pending changes" but the namespaces are okay.

1
Delete _MigrationHistory table and then tryvivek nuna
@viveknuna makes no difference. still "pending changes"-messageMatthias Burger
Can you delete your database? and then try if possible ?vivek nuna
@viveknuna been there, done that :D still same problem. also tried with setting Initializer to null and start without existing database...Matthias Burger
I think you can try enable automatic migrationvivek nuna

1 Answers

0
votes

Okay, the correct solution is easy:

When enabling migrations, in the newly created namespace Migrations the class Configuration is created. This class inherits from DbMigrationsConfiguration<TContext> and this inherits from DbMigrationsConfiguration. So, we don't need to create an instance with new DbMigrationsConfiguration() but with that generated new Configuration().

the correct code is:

public async Task<ActionResult> UpdateDatabase(UpdateDatabaseModel updateDatabaseModel)
{
    DbMigrationsConfiguration configuration = new Configuration();

    var migrator = new DbMigrator(migrationsConfiguration);
    migrator.Update(updateDatabaseModel.SelectedMigration);
    return this.View("ManageApplication");
 }

and that's it.