EF5 Code first migrations reset migrations - entity-framework

I was using EF5 code first and migrations right from the start.But I messed up something
and decided to reset my migrations.
I did enable-migrations -force
Then tried add-migrations xyz
I expected only to see incremental changes (addition of 2 tables)
Instead it tries to recreate every table.I dont want this to happen as it is shared via GIT and I need to push the migration also.
I have deleted all migration history and folder.What I want is a way to do another migration and it should only do the incremental create tables as other tables are already there

You need to do this in two steps:
Comment out your added tables and create an empty migration that updates the meta data to the state before those where added, by using the -ignore-changes switch (see my command reference)
Readd your tables and create a migration. Now it should contain only those two new tables.
Please note that whenever you mess manually with the migrations you need to be careful with the state of the metadata or you can get really nasty surprises.

Related

EF Core Migrations manual edits possible?

I am using EF Core 2.0 in my sample project with some value object configurations. I modify the code and generate migrations via CLI command line. In the last migration rather than adding a new database table as it should, it is trying to rename existing tables to each other and create an extra table for existing one. I could not figure out the reason for it.
Issue is, since with EF Core the snapshot is a separate auto-generated file from the migration itself I don't want to modify the snapshot.
I only want to modify the migration script so that it will not rename multiple tables, and then generate the snapshot from the migrations I created.
I did not see any command for this in the CLI - is it such a bad practice to modify the scaffolded migration and regenerate or am I missing some obvious new link where how to manually modify migration scripts is explained?
Thanks a bunch.
Update 1: After comments, added info about the snapshot from this link.
Because the current database schema is represented in code, EF Core doesn't have to interact with the database to create migrations. When you add a migration, EF determines what changed by comparing the data model to the snapshot file. EF interacts with the database only when it has to update the database. +
I examined my generated snapshot code from source control. It exactly has added one extra table as what I needed.
The migration script to generate this is hectic at best - renaming multiple tables to each other and then warning that this could break causing multiple issues.
Since this is a sample project for me with only mock data as of now at least, I decided to go for it and not break the automated scripts. I am willing to lose some mock data at this stage rather than wasting time on it.
If this were in a production database I would be extremely careful to manually create the same result with intervention modifying both the scaffold and the migration file.
I am accepting this one as an answer (basically saying current EF Core does not support it to the best of my current knowledge) since there is no other candidate now - I will be more than glad to accept if any better answer shows up.

Update model snapshot of last migration in Entity Framework and reapplying it

I'm using EF6 code-first migrations for existing database but initial DbContext does not fully cover existing schema (since it's massive). So from time to time I have to make updates to the model in database-first style. For example when I need an entity mapping for a table or a column that is already in the database but not reflected in the code I do the following:
Make all change (add new entity, rename the column mapping or add new property)
Scaffold migration representing the latest model snapshot stub_migration
Copy-paste latest serialized model from stub_migration to the last_migration resource file
Delete stub_migration
Revert last_migration in database
Update-Database so that model snapshot in [__MigrationHistory] table would be also updated
I understand that this aproach is a bit hackish and the proper way would be to leave empty stub_migration but this would force lots of empty migrations which I would rather avoid.
Looking at a similar scenario from MSDN article (Option 2: Update the model snapshot in the last migration) I wouldn't imagine that there is an easier way rather than writing power shell script, managed code or both to make it work. But I would rather ask community first before diving deep into it.
So I wonder: is there a simple way to automate generation of new model snapshot in latest migration and reaplying it?
I'm doing something similar. I have a large database and I am using the EF Tools for VS 2013 to reverse engineer it in small parts into my DEV environment. The tool creates my POCOs and Context changes in a separate folder. I move them to my data project, create a fluent configuration and then apply a migration (or turn automigration on).
After a while I want a single migration for TEST or PROD so I roll them up into a single migration using the technique explained here: http://cpratt.co/migrating-production-database-with-entity-framework-code-first/#at_pco=smlwn-1.0&at_si=54ad5c7b61c48943&at_ab=per-12&at_pos=0&at_tot=1
You can simplify the steps for updating DbContext snapshot of the last migration applied to database by re-scaffolding it with Entity Framework:
Revert the last migration if it is applied to the database:
Update-Database -Target:Previous_Migraton
Re-scaffold the last migration Add-Migration The_name_of_the_last_migration which will recreate the last migrations *.resx and *.Designer.cs (not the migration code), which is quite handy.
Those 2 steps are covering 4 steps (2-5) from original question.
You can also get different bahavior depending on what you want by specifying the flags -IgnoreChanges and (or) -Force
And by the way, the major problem with the updating the DbContext snapshot is not how to automate those steps, but how to conditionally apply them to TEST/PROD environments depending on whether you actually want to suppress the warning because you've mapped existing DB-first entities in you DbContext or you want it it to fail the build in case you've created new entities and forgot to create a code-first migration for them.
So, try to avoid those steps altogether and maybe create empty migrations when you just want to map existing tables to your code.

Migrating from EF5 to EF6 with existing migrations

Context:
I currently have a system built on Entity Framework 5, which we'd like to upgrade to 6.
However, it already has dozens of migrations applied. And not just that, we have unit tests that verify all migrations by creating a test database and updating to latest and back to initial, to ensure all Up and Down migrations can be properly applied.
From what I've been reading, if migrations have different EF version numbers, Update-database fails to cross that boundary, meaning, the unit test covering all migrations would never pass. I could be mistaken and EF migrations might be backwards-compatible.
Question:
In that scenario, would it be wiser to actually merge all old migrations into one large InitialCreate migration (recreated using EF6), deleting the MigrationHistory table and "fake-apply" the migration to the live database (by commenting out the code of that migration temporarily) to get the new history entry?
And second of all, is this something we'll have to do again when updating EF in the near future? If that's the case then it might seem like EF is missing some support regarding cross-version migrations.
I ultimately ended up implementing what I described above in the question itself. All this was done AFTER migrating everything to EF6.
In my case I not only needed to apply this to my local database but to a live database as well.
The steps I used to accomplish that where the following (hopefully I'm not forgetting any, since this was a while back):
Backup your databases (both local and live), just in case you need to undo this.
First we need to create one merged migration for the entire database.
Change your ConnectionString to point to a new blank database.
Physically delete all migrations from your solution, as well as your initial creation one.
Run Add-Migration InitialCreate, which should add a migration to regenerate the entire database.
Now you don't really want to run that migration. In my case I only need that for unit tests, or to create new databases from scratch.
So then we continue:
Change your ConnectionString back to your local database.
Physically delete the MigrationHistory table in the database (or possibly just remove the rows, I can't recall exactly).
Comment out ALL the code whithin the InitialCreate migration, to make sure it will do nothing when applied.
Run Update-Database, which should add an entry to the MigrationHistory table simulating an initial creation of the database.
Uncomment the code in the InitialCreate migration.
The same process can be applied for the Live database. You can point to it in the ConnString, manually remove migration history, comment the implementation of the migration and apply it, to simulate creation, then uncomment.
From then on, the database and migrations should be in sync, and unit tests (on a separate database) should be able to call Down() and Up() on all migrations and still function properly.
I had also done same thing today (5-May-2014) and did not face issue mentioned by you
and had used steps suggested in
http://msdn.microsoft.com/en-us/library/upgradeef6.aspx
so my old migrations still remains the same.
Though i faced some other issues related to
- Miniprofiler (need to use new with EF6 support)
- and one issue related to re-creation of all index after upgrading.

Entity Framework 5 Code First - How to "start over"?

I've been using EF 5 Code First, successfully, in my app. I have roughly 40 tables. However, I've run into an issue that I can seem to get Migrations to handle correctly. So, what I would like to do is to somehow tell EF to treat the current schema of the database as a new starting point, and start managing it from this point. This way, I can make the necessary schema change manually, and then tell EF to essentially start over from this point.
Is there a way I can do this? I presume I'm going to have to delete the __MigrationHistory table, or remove its contents. But I'm not sure how best to proceed with doing this.
You should be able to do the following:
Change your database manually to reflect the changes in the model that wont be handled by a migration. Everything should work now, but the database and the migration system are out of sync.
Run Add-Migration ManuallyUpdatedDatabase -IgnoreChanges. This creates a migration that is completely empty, so it wont make any changes to the database, but it will make sure that the system knows about the manual changes that have been made. That way the manual changes wont be included in the next migration you create.
Run Update-Database to apply the empty migration.
From here on everything should work as usual. You just have a "missing link" in your migrations because you have handled some changes manually.

EF Data migrations won't detect changes when adding new migration

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.
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.
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.
The problem in my case was caused by:
Create a migration (successfully)
Decide that I want to re-create it, and delete the migration .cs file
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.
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.
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').
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.
The batch build -> clean option did not work for me.
I solved the problem by:
Creating a migration with 'Add-Migration NameOfMigration'
Deleting the contents of the up and down functions of the created migration class.
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.
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. :-)
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.
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 :(
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
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.
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.
Maybe the stupidest of all:
I was adding a migration with the same name as the new object I was creating.
I had to run dotnet ef migrations remove even though I'd deleted the previous migration
If you are using fluent api to set up your configurations for the DbSets then you won't have any problems with it