50

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Moulde
  • 3,438
  • 4
  • 29
  • 38

17 Answers17

49

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.

naskew
  • 2,091
  • 1
  • 19
  • 20
  • 3
    This was my problem as well. If the new entities are not referenced by a context with `DbSet` they apparently don't get picked up. – jocull Nov 14 '16 at 15:30
  • +1 for this, your entities must be included in the ApplicationDbContext (or whatever it is you're using) as DbSet otherwise they won't be generated as part of a Migration script. – Steve Woods Nov 22 '16 at 13:44
  • Also, if you are using Fluet API make sure that table relations are right. In my case I had a nullable FK. The field was marked as nullable in the model and as IsOptional in configuration but I forgot to update the many to many relations. ```/*Forgot to replace HasRequired with HasOptional*/ HasOptional(a => a.License).WithMany(b => b.Stores).HasForeignKey(c => c.LicenseId).WillCascadeOnDelete(false);``` – Vector Jan 13 '17 at 02:44
  • Here I am, at midnight, putting new models in the migration before I call it a night and I'm scratching my head... and then I'm like... "oh yeah... duh, adding it to the dbcontext". *sigh* I gotta go to bed. – Paul Carlton Dec 02 '18 at 09:49
47

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)'.

Hope this helps someone else out there.

Shaun Wilson
  • 8,727
  • 3
  • 50
  • 48
  • This wound up being my issue too. I don't suppose you have any information on what actually had to be cleaned in order to fix this? – Andrew Edvalson Jan 26 '15 at 22:13
  • 4
    In all my years using VS I never even noticed Batch Build.. I figured Clean Solution would do the same thing but it didn't.. only Batch Build > Clean worked. Thanks – parliament Jun 20 '15 at 21:13
18

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.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Michel Marchand
  • 181
  • 1
  • 3
17

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.

Christian Rondeau
  • 4,143
  • 5
  • 28
  • 46
  • 2
    Thank you! I too forgot to delete the entries in `ApplicationDbContextModelSnapshot.cs`, which caused the new migration to be empty. – Daan Apr 17 '18 at 09:41
  • 1
    @Christian Rondeau where can I find the ApplicationDbContextModelSnapshot.cs file? – JP Dolocanog Jun 26 '20 at 12:52
  • @JPDolocanog It should be in your project, I don't remember the exact folder but if you don't find it in your source files, then I don't know... – Christian Rondeau Aug 27 '20 at 15:05
10

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').

Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
  • Where is this "migration table"? – Chuck Savage Oct 27 '17 at 07:40
  • @ChuckSavage - I didn't check with recent versions, but it was under system tables I think, prefixed with "__" – NSGaga-mostly-inactive Oct 27 '17 at 08:19
  • This was indeed the problem for me. I tried to run a migration that would have led to data loss (intentional) and it got refused. I did it again, with the -Force flag, and it worked, but it created an "Automatic migration" that was causing disalignment. Deleting it solved for me. – Tu.Ma. Feb 28 '19 at 11:26
7

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.

joelmdev
  • 11,083
  • 10
  • 65
  • 89
5

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.

Ryan Spears
  • 2,963
  • 2
  • 31
  • 39
2

It happened to me and nothing worked. Then i did this on my own and everything works now.

Problem: I created a Model "Cars". And When I create a migration for it using command "add-migartion AddCarModel", a migratoin was created but it was empty. I tried with different names and also tried delete migration's .cs file but nothing worked. Then I did the following:

Solution: Follow below steps:

1. Delete all the empty migrations that you created for the Model. (But remember the names of the migrations for step 2)

2. Also delete those migration entries from "_MigrationHistory" table.

3. Comment out you line(s) of your model DB context, (in my case it is "public DbSet Cars{ get; set; }")

4. Clean and Rebuild solution. (Its best that if you batch clean)

5. Make sure that your update command is working and not throwing errors. (Command: "update-database -verbose")

6. Now uncomment line(s) that you commented in step 3.

7. Now create the migration for that model. (I created the migration with same name as before)

Hopefully it works. :-)

Zeeshan
  • 121
  • 1
  • 3
1

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.

  • 1
    All I did was add `public DbSet Vehicles { get; set; }` inside my ApplicationDbContext class definition, ran a new migration and it picked it up! Thanks Rob – SendETHToThisAddress Nov 03 '20 at 18:14
0

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 :(

Moulde
  • 3,438
  • 4
  • 29
  • 38
0

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

kidra.pazzo
  • 195
  • 8
0

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.

aoakeson
  • 602
  • 1
  • 8
  • 20
0

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.

Joshua Morgan
  • 678
  • 6
  • 18
0

Maybe the stupidest of all:

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

RazvanR
  • 412
  • 5
  • 14
0

I had to run dotnet ef migrations remove even though I'd deleted the previous migration

Benjineer
  • 1,530
  • 18
  • 22
0

If you are using fluent api to set up your configurations for the DbSets then you won't have any problems with it

S.Minchev
  • 73
  • 8
0

The reason I didn't work for me was because of refactoring the database out into it's own project, but leaving the migrations in its original project with their original namespaces...

So after moving the migrations next to its new home, and changing the namespaces to match with the namespace of my Database class which inherits from DbContext, the migrations were detected again.

bas
  • 13,550
  • 20
  • 69
  • 146