Issue with entity framework migration. [Unable to generate an explicit migration because the following explicit migrations are pending] - asp.net-mvc

I am using EF code first and asp.net MVC. Here is my technical stack.
Visual Studio 2010
Entity Framework 4.3.1
In my migrations folder, I can see three migrations files are existing.
InitialCreate
AddStandardException
DocumentScope
When I check my database I can see that _MigrationHistory table has all three migrations applied. Now I have added one more DbSet, and I want to write migrations for it. When I attempt to give this command
Add-Migration NewTable
It gives me this error :
Unable to generate an explicit migration because the following explicit migrations are pending: [201402121621095_AddStandardException, 201402190713571_DocumentScope]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
I don't understand why is it complaining about pending migrations whereas all migrations have been applied?
How do I even troubleshoot this ? I tried with -Debug switch but no luck.

I found a workaround to it. I have just commented code inside the Up() and Down() functions. Then ran Update-Database. It applied some dummy migrations and then reported that
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.
After this when i ran
Add-Migration NewTable
It gave me the correct result. Any idea whats going on here ?

You either need to run "update-database" from the package manager console to push your changes to the database OR you can delete the pending migration file ([201402121621095_AddStandardException]) from your Migrations folder and then re-run "add-migration" to create a brand new migration based off of your edits.

Explanation: "update-database" basically modifies existing table fields while "add-migration" works like git by making a snapshot of the distinct model changes. These snapshots show how the database evolved over time so they are more useful to your code user than the EF or the App itself.
That being said, it is possible that your newer classes have a quite different code signature which may not "flow" with the existing classes.
Solution: Modify or remove the previous migrations since the new migration will create a new data structure that won't use or need them

Related

EF6 Updating Code First Model from the Database

I inherited an ASP.NET MVC application using Entity Framework 6.2. The application was originally built using Code First and I can see migrations that have been applied to the database. The structure of the database seems accurate.
However, a ton of relationships have been added to fix referential integrity issues and these were done directly on the database. There are a bunch of them. Can someone help me to update the models from the database in a code first implementation? Ideally it would remain code first, not a conversion, but I need to do a one time update.
I'm more familiar with newer EF Core and I thought it would as easy as running a scaffold-dbcontext command with a -force and some cleanup. But no such luck in this older version. Is there something similar?
Depending on what a 'ton' means and whether you need to keep the old migrations you could either just rebuild the entire model by doing code first from existing database or you could save the generated code into a folder and do a manual reconstruction:
Run code first from existing database into a new folder.
Map new fields and navigation properties into existing models.
Fix up any fluent code (modelBuilder).
Generate a migration which should include those changes.
A good test would be restoring a pre-change version of the database and running the migration against it. Then perhaps use a schema compare utility.
Apply the migration to databases. If the database already includes the changes, comment out the Up() code before applying. This will update the stored model so the next migration does not repeat these changes.

How do you downgrade a Entity Framework 5 migration in Visual Studio 2012?

I've noticed that when I create a code first database migration using add-migration it generates a Down() method as well as an Up() method.
How do I tell my database to downgrade?
After almost giving up with researching on Google I managed to find this quote from here:
http://msdn.microsoft.com/en-gb/data/jj591621.aspx#specific
Which Specifies:
Let’s say we want to migrate our database to the state it was in after running our AddBlogUrl migration. We can use the –TargetMigration switch to downgrade to this migration.
Run the Update-Database –TargetMigration: AddBlogUrl command in Package Manager Console.
This command will run the Down script for our AddBlogAbstract and AddPostClass migrations.
If you want to roll all the way back to an empty database then you can use the Update-Database –TargetMigration: $InitialDatabase command.
First get the name of the migration that was applied before the one you want to downgrade by issuing the Get-Migrations command.
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201508242303096_Bad_Migration
201508211842590_The_Migration_applied_before_it
201508211440252_And_another
This list shows the migrations listing the most recent applied migration first. Pick the migration that occurs in the list after the one you want to downgrade, ie the one applied before the one you want to downgrade.
Update-Database –TargetMigration: "<the migration applied before it>"
All migrations applied after the one specified will be down-graded in order starting with the latest migration applied first.

Code Migrations is skipping initial code migration

Using Entity Framework 5, we're using Code-First Migrations in our application. Every developer has his own database on which they work.
I have accidently emptied mine: There is nothing in there anymore, no tables, not even the migration history table.
So, I've tried to update the database again through the PM console by executing update-database. It immediatley gives me an error that a table does not exist, while it should be created in my inital code migration.
What is interesting is that the PM console also shows what migrations are being applied, which does not contain the inital create code migration, thus not creating any tables at all, and ofcourse failing at later migrations.
I tried executing update-database -targetmigration:initialcreate which gives me the message that that code migration does not exist, while it is a direct copy/paste from the cs file, so the id must be correct (note: this works for other migrations).
I also tried update-database -targetmigration:0 and update-database -targetmigration: $InitialDatabase which both give me 'Target database is already at version 0'.
I've also tried deleting the database altogether and let EF create it for, didnt work either, it keeps skipping the initialcreate migration.
So how do I get Code Migrations to execute my initalCreate code migration?
Working with EF migrations in a team scenario is not ideal to say the least. The best practice my team follows is to never commit migrations. Migrations are personal and apply only to your particular database instance. If everyone commits their own migrations you end up with a mess, quick.
While not directly related to your question, some may wonder how you deal with production migrations. Simply, you don't. Your Release Manager, or whoever will actually push the release live, should generate SQL to apply all the changes at once, and then hand this off to your DBA, or whoever manages the production database.
That said, in the scenario that you describe, where you database has been emptied. The best fix is to delete all migrations in your Migrations folder. Even and especially, the initial migration (they don't matter, anyways, because you shouldn't be holding on to them outside of your personal codebase). Then generate a new migration, which will trigger EF to compare your current database state (empty) with the state of the app and essentially create a new initial migration based on the current state of your app. Then, you can apply this migration.

Entity Framework 4 code-based migrations don´t work after calling CreateDatabaseIfNotExist

I have a MVC 3 project were I use code based migrations together mith automatic migrations(this works).
When I install this project on a new server the database is created by CreateDatabaseIfNotExist initializer, cause I´m using the seed method of this. After executing this I have a __MigrationHistory table with one entry. The model hash of this entry is exactly the same like the last one from my developement server. On my development server I have an entry for each of my code based migration in the __MigrationHistory table.
Now the problem is that when I try to run the migrations on the new server, I expected them to say to me "nothing to do, cause model hash is same", but instead of this the migrations seems to look only for the MigrationId in the database and try to execute every migration whose MigrationId is missing. Of course this leads to Exceptions, cause the migration tries to add database structures already there.
I think this should be a very common scenario, so is there a kind of workaround for this? My workaround for the moment is to copy all contents from the __MigrationHistory of the development system to the new server, but this is very tricky, due to the dealing with the modelhash as varbinary. Is there a better solution or did I understand some logical things wrong?

Getting Initial Entity Framework Migrations Script

I just installed Entity Framework Migrations, added a property to a class, and gave EF Migrations a whirl.
My development database was promptly updated. So far, so good.
Now, I want to create a change script for this initial use of Migrations for the production database. Note there was a pre-existing database because I applied this to an existing project.
The migrations I have are:
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201204102238194_AutomaticMigration
201203310233324_InitialCreate
PM>
I thought I could get a delta script using the following:
Update-Database -SourceMigration:201203310233324_InitialCreate -TargetMigration:201204102238194_AutomaticMigration -script
However, that gives me the error:
'201204102238194_AutomaticMigration' is not a valid migration.
Explicit migrations must be used for both source and target when
scripting the upgrade between them.
Just to see what would happen, I reversed the two parameters (backward migration) and did get the script I would expect after adding the -force flag (new columns dropped).
How can I get a script for this first migration?
The right way to start using EF migrations with an existing database is to start with adding an empty migration that contains the metadata of the current database.
I think that you have to roll back to a model that is compatible with the initial database schema. Then run the following command:
add-migration InitialSchema -IgnoreChanges
That should give you an initial migration, that does nothing, but contains the metadata of the current model. You can of course add migrations later with -IgnoreChanges if you've expanded your code model to cover more of the tables already present in the database.
Once you have that initial migration step in place, the scripting would work.
Generally I would not recommend to use automatic migrations unless you only ever intend to only use automatic migrations. If you want some kind of control over the changes to the database (including scripting them) then code-based migrations is the way.

Resources