Search code examples
entity-framework-6database-migrationentity-framework-migrations

Detect if Entity Framework model is too old for database using MigrationHistory


We switched from manually coding database migrations to code-first Entity Framework migrations. In our old setup we were able to check whether the database is too new. This is important because it will probably be incompatible. Unfortunately I can't find a nice way to check how up-to-date the current database is or whether it is too old.

The use case is that a client has 2 versions of our software on his computer. The client first starts the newest version that contains more recent migrations than the older version. Afterwards the client starts the older version of the software. Currently the software will crash and burn because the model is incompatible.


Solution

  • You can use

    DbMigrator.GetPendingMigrations
    

    to check if the database is in sync

    You can use

    DbMigrator.GetDatabaseMigrations
    

    to check what migrations have been applied to the target database.

    And then run the pending migrations as required:

    var configuration = new Configuration();
    var migrator = new DbMigrator(configuration);
    migrator.Update();
    

    http://romiller.com/2012/02/09/running-scripting-migrations-from-code/