Search code examples
entity-frameworkef-code-firstcode-firstentity-framework-migrations

EF migrations won't recognize existing tables


I've set up this project from DB first and everything went fine. I can debug properly. But when I try make a change to one of my models, instead of the new migration showing a simple AlterColumn statement, it keeps trying to reinitialize the entire database.

I've tried running update database -script and only inserting the _MigrationHistory table record. Even after that, it still wants to create all the tables.

Has this ever happened to anyone?


Solution

  • When you start with an existing database you need to do an empty (no-op) migration to set a baseline. This is because EF will use the model in the prior migration to compare, so if there is not one (in code) you get all your database objects. Inserting a record into __MigrationHistory just tells EF the code migration has been applied - it doesn't use it for the compare.

    enable-migrations

    add-migration MyBaseline -IgnoreChanges // no Up() code, but model saved

    update-database

    // Now I can change my model and generate a migration with difference

    See here.