Scaffold migration with context key change

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


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.

1/25/2017 7:44:40 AM

Accepted Answer

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
5/23/2017 10:31:20 AM

Popular Answer

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 changed namespaces in merged project to all migrations and configuration itself to new namespace value.
  • I executed following statement against database:

    USE [DatabaseName]
    UPDATE [dbo].[__MigrationHistory]
       SET [ContextKey] = N'NewNamepacePlusConfigurationClassName'      
     WHERE ContextKey= N'NamepacePlusConfigurationClassName'
  • 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

Related Questions


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