EF Data migrations won't detect changes when a

2019-02-07 18:02发布

问题:

I am using Entity Framework 5.0 Data migrations along with code first. When i add a new field to my model and execute the following command in the package manager console.

 "Add-migration AddedField"

All I get is an empty migration called "n_AddedField", the up and down methods contain no logic.

I tried a bunch of things, reinstalling the EF nuget package, cleaning my solution, rebuilding, manually removing all generated files and directories.

Then i decided that i would scrap all my migrations and start over, and then it got weird. After deleting all my migrations, and the migrationhistory table in the database, i recreated the database using the CreateDatabaseIfNotExists initializer. After doing this, I should be able to create a new initial migration. But when i try to create create a new migration, I get an error saying that there are pending migrations, and lists all the migrations that i just deleted from my project.

I have no idea why and how EF still has any recollection of those migrations. I even tried searching through filecontents looking if the migrations were saved somewhere else or something. But nothing..

Data migrations look really neat when scott hansleman demo's it on stage, but for real work, I'm starting to look for alternatives.

When the project started, we were using EF 4.x and a while back switcted to 5.0, but since the switch i have added a bunch of migrations successfully.

Does anyone have any idea how to solve this problem? Basically i just want to be able to add migrations, and generate a sql script with the changes.

回答1:

I had a similar problem where a new migration was not being found, and so update-database was giving me the following error no matter what I did:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
You can use the Add-Migration command to write the pending model changes to a code-based migration.

Doing a "batch clean" solved my problem, suggesting EF was using an old/invalid assembly from a folder other than the currently selected 'solution configuration (e.g. DEBUG)'.

To do a batch clean:

  1. Select Main Menu -> Build -> Batch Build...
  2. Click Select All
  3. Click Clean

Close dialog, rebuild and re-attempt migration.

Hope this helps someone else out there.



回答2:

oops. In my case I was adding a new root entity not referenced by any other entity. The result was simply that code first had no reason to generate a migration for the entity. Once I added the code into the DbContext (a dbset) it worked like a charm.



回答3:

Just got the same problem but figured out that my new field was added as a member variable and not a property - it was missing the {get; set;} part and that makes migration skip that field.

May not be your case but it might help someone else.



回答4:

I had a problem similar to this, where using the -force flag on add-migration to re-scaffold an existing migration stopped working for no apparent reason.

No matter what I did I got the stupid "Unable to generate an explicit migration because the following explicit migrations are pending" error message. After trying nearly everything I could think of and stopping just short of smashing my laptop to pieces, out of desperation I ran enable-migrations again and of course got the "Migrations have already been enabled in project 'Blah.Blah'" message. Tried add-migration -force again and magically it was working.

I have no idea what it changed- must have been some user settings/config file outside of source control. Hopefully this will help someone else.



回答5:

You're 'out of sync' - Db, migrations, code - and you can expect all sorts of problems like that.

I did this million times (almost:) and it works really well - but you need to go steady, and be meticulous with what you're doing.

You can read through this 'summary' I made - start half-way somewhere (but also check connection).

Code first create tables

...and if it doesn't work I'd suggest you make a small 'repeatable' scenario / model - post exactly what you have.

How migrations work:

Migrations are tied to the 'migration table'.

When Add-Migration is run - it checks against the 'existing database' structure and migration table - and makes the 'difference' (sometimes you get none 'up' 'down' simply as too are in sync).

So, each 'migration' is a complex diff in between your code, existing migrations, and database, and migration table. Short of removing the database nothing else is certain to reset - Db 'migration' table may not be enough - that doesn't guarantee full 'cleanup' (if possible, I always do full Db delete). You also need to delete your code migrations.

Make sure to 'compile' the projects (best make them compile automatically in configuration) after/before where relevant.

Make sure your 'connection' matches.

Once all is in sync - all should work nicely - but you gotta keep it in sync. Unless you plan to delete the Db (testing) - don't remove migrations just like that (you can use Update-Database -0 (I think) to get back to some migration (this is 'zero state').



回答6:

The batch build -> clean option did not work for me.

I solved the problem by:

  1. Creating a migration with 'Add-Migration NameOfMigration'
  2. Deleting the contents of the up and down functions of the created migration class.
  3. Updating the database by running the migration script (which will just add a row to the _MigrationHistory table with 'Update-Database -Verbose'

The web application now runs successfully, so essentially I had an issue that was fixed by adding meta-data only.



回答7:

The problem in my case was caused by:

  1. Create a migration (successfully)
  2. Decide that I want to re-create it, and delete the migration .cs file
  3. Try to regenerate it, and end up with empty migration's Down and Up functions

In this case, I forgot to also delete the ApplicationDbContextModelSnapshot.cs entries for the model changes. Removing the new mappings in this file solved my problem and it then generated correctly.



回答8:

It seems that i managed to solve the problem by moving the models and the context class to another project.

I still have no idea why this happened, and this solution is really no solution at all :(



回答9:

I had the same problem. Migrations were enabled but they weren't detecting any changes. My solution was to re-enable migrations using -Force attribute and then everything worked.

Enable-Migrations -ProjectName -StartupProjectName --ConnectionStringName -Force



回答10:

I had to delete the _MigrationHistory table that is generated by EF. Then I ran add-migration again. Be careful with this though, as it will generate the queries needed from scratch, including tables that are already there.



回答11:

In my case it was because I had added a secondary context 'ApplicationDbContext' as part of the ASP.net identity stuff. When I ran the 'enable-migrations' command again I got an error that there was more than one context. Once I combined the two things started working again.



回答12:

Maybe the stupidest of all:

I was adding a migration with the same name as the new object I was creating.



回答13:

I added a new class to my data model to a sub-directory, the resultant namespace was not visible to scaffolding using add-migration.

Fix was to rename the namespace of the new class to conform to the rest of model, and/or add "public virtual DbSet .." etc into your entity context class, which will require you to reference this new namespace, then run add-migration again.



回答14:

Don't forget to include Public access modifier:

public string Text { get; set; }