3

I have EF migrations enabled and want to update an existing database running in azure. When I run the application I get the following exception:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

However I have migrations enabled.

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());

And

internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
    public Configuration()
    {
         AutomaticMigrationsEnabled = false;//have also tried true
    }
}

Up until this latest commit everything has worked automatically as expected and i haven't changed the initialization code (only added new migrations).

If i download the database and run the app I get the same result. However if I manually run Update-Database everything works as expected.

Is there a way to get this to run via code as I cant run Update-Database inside Azure.

undefined
  • 33,537
  • 22
  • 129
  • 198
  • `AutomaticMigrationsEnabled = true`? – Dennis Feb 22 '14 at 08:08
  • I tried that, it didnt work, im pretty sure that setting is for automatically updating without migration files – undefined Feb 22 '14 at 08:09
  • You're wrong... `AutomaticMigrationsEnabled` manages, how migrations should be applied - either during context initialization or manually, using `Update-Database`. Of course, automatic migrations could be applied, if user account has sufficient rights to update database schema. What *exactly* didn't work with `AutomaticMigrationsEnabled = true`? – Dennis Feb 22 '14 at 08:13
  • @denis I get the same exception. It definitely does work with this set false as it has been set to false since I added migrations to the solution. I've done plenty which worked correctly before now. CF http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/ – undefined Feb 22 '14 at 08:19
  • @denis also see http://stackoverflow.com/questions/11806570/automaticmigrationsenabled-false-or-true – undefined Feb 22 '14 at 08:21

1 Answers1

3

I found my (stupid) mistake, I hadn't changed the initialisation code but i had managed to deregister it so it wasn't getting called.

I moved it to the static constructor on my context and all was happy.

static MyContext()
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
}
undefined
  • 33,537
  • 22
  • 129
  • 198