I have restructured my project which led to a change of namespace name of the database context and associated Code First configuration. At that point, I've had one scaffolded migration, "InitialCreate" and thus my database's __MigrationHistory
table contained a single row with some MigrationId
and a ContextKey
containing the namespace name and class name of the Configuration
class.
After I've moved things around, executing Get-Migrations
returned no results, after changing the ContextKey
as per my colleague's advice, the "InitialCreate" migration was correctly enumerated.
What steps should I have taken during the changes so the continuity of my migrations wasn't broken, preventing the need to rename the ContextKey
by hand? Obviously, that's no big deal for one applied migration, however it'd be a huge pain to do for dozens of applied migrations.
I was stuck in this for a long time and asked-and-answered-it here. In the EF docs you can find the explanation about context keys here.You should create custom migration configuration like this :
public class MyMigrationConfiguration : DbMigrationsConfiguration<MyMigrationContext>
{
public MyMigrationConfiguration ()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
MigrationsNamespace = "My.Migrations.Assembly";
MigrationsDirectory = "My/Migrations/Directory";
ContextKey = "MyContexKey"; // You MUST set this for every migration context
}
}
I had two separated database projects - one containing model and mapping, other one containing only migration configuration and all migrations. I've merged project containing migrations into project containing model, etc.
Finally I solved problem with impossibility to add new migration or keep database up to date or migrating schema to previous state by making those steps:
I executed following statement against database:
USE [DatabaseName]
GO
UPDATE [dbo].[__MigrationHistory]
SET [ContextKey] = N'NewNamepacePlusConfigurationClassName'
WHERE ContextKey= N'NamepacePlusConfigurationClassName'
GO
I build project containing migrations with configuration
Now everything works as expected, I'm even able to change schema backwards using statement
Update-Database -TargetMigration PreviousMigration