Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbMigrator trying to execute every migration, not detecting executed migrations

I am trying to create a service call that will update an EF code first database to the latest version. However, it is always trying (and failing obviously) to execute all migrations, whether they were executed already or not.

Here's my code:

        var config = new DbMigrationsConfiguration<MyContext>();
        config.MigrationsAssembly = typeof (MyContext).Assembly;
        config.MigrationsNamespace = "Context.Migrations";

        //This had no effect
        //config.SetHistoryContextFactory(connectionString.ProviderName, (connection, s) => new HistoryContext(context.Database.Connection, "dbo"));
        var migrator = new DbMigrator(config);

        //This gets every single migration, even the ones already executed before
        var migrations = migrator.GetPendingMigrations();
        //This gets 0 migrations
        var existing = migrator.GetDatabaseMigrations();
        //This gets all migrations
        var other = migrator.GetLocalMigrations();

        //This returns true! So it knows all the migrations are already executed
        var differ = context.Database.CompatibleWithModel(true);
        //This will throw an exception because it's trying to create existing tables!
        migrator.Update();

I can confirm that the migration history table contains [dbo].[__MigrationHistory] references all the old migrations.

I checked the connection strings in the migrator. I also tried setting the history context factory manually in case it is looking somewhere else with no result. Also, running update-database directly from the console works and says no pending updates.

Any help is appreciated

like image 637
Charbel Avatar asked Mar 14 '23 13:03

Charbel


1 Answers

Make sure DbMigrationsConfiguration.ContextKey is set correctly.

The default value after this line

var config = new DbMigrationsConfiguration<MyContext>();

will be like this

"System.Data.Entity.Migrations.DbMigrationsConfiguration`1[MyContextNamespace.MyContext]"

You need to add the following line

config.ContextKey = "{Your_Context_Key}";

If you don't know the context key, open your [dbo].[__MigrationHistory] table and look at the ContextKey column.

Once you set it up correctly, if your database is up-to-date, migrator.GetPendingMigrations() should return empty and migrator.GetDatabaseMigrations() should return all migrations.

like image 140
Ivan Stoev Avatar answered Apr 27 '23 08:04

Ivan Stoev