Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does EF 6 ignore applied migrations if I move the Migrations folder?

When I first ran Enable-Migrations in my project, it created a Migrations folder under the project root. Then, I moved the Migrations folder to under my Data folder, where the context and models etc. are. Then I corrected namespaces in both already applied migrations.

Then I tried a third migration with Add-Migration IdToLong, and I got an error saying:

Unable to generate an explicit migration because the following explicit migrations are pending: [201703061039495_Initial, 201703061159110_ContactRequest]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

The only reason I can think of is that EF has stored a relative path to the location of the connection string, and that path is now useless. I have seen several reports that EF shows the same message when unable to connect to the database.

This hidden storage/config for EF goes against the grain of where we are moving with EF Core, and I really hope this problem doesn't occur there.

To get to my question then, what changed or didn't change when I moved the Migrations so that EF could no longer see that I had already applied those migrations?

like image 250
ProfK Avatar asked Mar 07 '17 10:03

ProfK


1 Answers

When you move migrations, you may have (probably) changed the namespace of the objects. This namespace is used as the default for the ContextKey column in the __MigrationHistory table. So now when EF checks which migrations have been applied it won't match the old ones.

If this is your issue, you can fix it a couple of ways:

1) Run a script to rename the context keys to match your new namespace:

UPDATE [dbo].[__MigrationHistory] 
   SET [ContextKey] = 'New_Namespace.Migrations.Configuration'
 WHERE [ContextKey] = 'Old_Namespace.Migrations.Configuration'

2) Hard code the old context key into the migration configuration constructor:

public Configuration()
{
    AutomaticMigrationsEnabled = false;
    ContextKey = "Old_Namespace.Migrations.Configuration";
}
like image 153
Steve Greene Avatar answered Oct 08 '22 11:10

Steve Greene