Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaffold migration with context key change

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.

like image 960
Tomáš Hübelbauer Avatar asked Dec 15 '14 12:12

Tomáš Hübelbauer


People also ask

How do you specify context in migration?

Using multiple context types One way to create multiple migration sets is to use one DbContext type per provider. Specify the context type when adding new migrations. You don't need to specify the output directory for subsequent migrations since they are created as siblings to the last one.

How do I update my database in migration?

After creating a migration file using the add-migration command, you have to update the database. Execute the Update-Database command to create or modify a database schema. Use the –verbose option to view the SQL statements being applied to the target database.


1 Answers

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
    }
}
like image 125
Ognyan Dimitrov Avatar answered Sep 22 '22 11:09

Ognyan Dimitrov