Entity Framework always has pending migration - entity-framework

Using Entity Framework 6, with a SQL Server database and code first migrations, I have migrations set up and running "happily", however I'm finding that every time I go to add another migration I get the following error first off:
Unable to generate an explicit migration because the following explicit migrations are pending: [201602090629398_Initial, 201602090638322_FixSitePageColumns, 201602110313468_RemoveRequiredTemplateId]. Apply the pending explicit migrations before attempting to generate a new explicit migration."
If I run update-database -force it complains (naturally) that the script fails because of already having been applied. A strange combination of doign this again and then the add-migration works and I can carry on updating to the latest migration.
The list of "pending" migrations also grows with every addded migration over time.
What could cause this "pending" state, when the migration HAS already been applied? I can confirm that the database has already been updated, the migration exists in __MigrationHistory, and the program is running along happily.
EDIT
I've also just run get-migrations and the following is being returned:
PM> get-migrations
Retrieving migrations that have been applied to the target database.
201602110313468_RemoveRequiredTemplateId
201602110311536_RemoveRequiredTemplateId
201602090638322_FixSitePageColumns
201602090629398_Initial
The weird thing here (possibly a red herring) is that 201602110311536_RemoveRequiredTemplateId is not a migration in my project, I think it may have been one that I created and then deleted, I didn't ever implicitly apply it to the database but it's in the __MigrationHistory table.

This happened to me because when running Add-Migration it couldn't connect to the database to see what migrations had been applied. I don't have my password stored in the connection string. The fix was to run Add-Migration specifying a complete -ConnectionString and -SqlProvider
Add-Migration MigrationName -verbose -ConnectionString "data source=foo.database.windows.net;initial catalog=FOO_DB;user id=admin;password=`"REDACTED`";MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient"

Remove the entry for removerequiredtemplateid from the migrations database table and rerun your migration procedure.
Optionally, delete the table altogether, delete all of your migrations, rerun enable-migrations, create a new initial migration and run update-database again (basically, create a fresh start).
Remember to make the required backups beforehand.

Related

How to Cleanup & generate fresh migration for existing DB?

We wish to get rid of 100s of migration classes as DB schema in production is final.
Here are the steps I followed:
Delete Migrations folder.
Add-Migration -??
What command line switches, could help us?
EDIT:
If all goes well Up() method of migration should be empty right? For
example following is wrong generation on Add-Migration. Because if we
execute the project we will get duplicate table errors.
public partial class Sanity : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AccountPreferences",
c => new
{
AccountID = c.Guid(nullable: false),
}
.... for 1000s of tables
}
}
A clean migration would be something: when trying Add-Migration on subsequent changes, should not be getting any error.
Unable to generate an explicit migration because the following
explicit migrations are pending: [201712281054591_Sanity]. Apply the
pending explicit migrations before attempting to generate a new
explicit migration.
As you can see if we happen to execute Update-Database will get table already exist error.
Are we forced to always retains all migration copies?
See if this can help:
MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"
Entity framework code first - how to run Update-Database for production database
How to delete and recreate from scratch an existing EF Code First database
note:
I'm writing this from memory, if you have issues let me know and I'll recheck exactly.
Also, my knowledge on this is from slightly older versions of EF as I haven't done much work there recently, but I doubt much has changed.
From what I can tell, if you want to...
a) keep the db,
b) clean your project migrations,
c) have the 2 'match', be in sync:
do the following:
- Remove the migration folder (your project)
- Run Add-Migration Initial - then should add one migration
- caution: it is safe but do backup, change connection string etc. before the next step
- Run Update-Database -Script - that doesn't update the db but creates the SQL script, including the migration table
- find the INSERT INTO [__MigrationHistory] records, just run those (on your db), insert them into the database
...then test with Add-Migration again, to see if it is going to make anything, should yield no new migrations, empty one.
Please read through the first link above and adjust approach as needed.
I'm sure there might be easier, shorter ways to do this (via PM console) but unaware of it at the moment.
Open your database.
Clear table __MigrationHistory
Remove migrations in the folder
Run Add-Migration MigrationName
Almost the same as accepted one, but no scripting the initial migration.
Drop the __MigrationHistory db table
Remove all the migration files in the Migrations folder
Run Add-migration Initial in Package Manager Console
Comment out the code inside of the Up method in the Initial Migration
Run Update-database in PM Console (just to create a Migration Entry)
Remove comments in the Initial migration
Wonder how long it will be "final" ?
Use:
Add-Migration Initial
After removing the migrations folders

Entity Framework core won't update database

I successfully created an Entity Framework Core migration and updated the database with it.
Then after I added another class, I created a second migration called "update1" which created a class of the same name from the command line tools.
However, when I attempt to update the database, it fails.
Here is the commands I used
dotnet ef migrations add update1 -c MyDbContext
dotnet ef database update update1 -c MyDbContext
and it failed with
There is already an object named MyTable in the database
which is a table which was created in the initial migration.
How can I tell it to either ignore the error, or else to only attempt to run the update1 migration?
Edit: deleting the table that was already there caused this odd behavior to stop happening and now it works as expected.
Thanks
You have to remove the unwanted migration from the __MigrationHistory table.After that you can run your latest migration.This is happened due to you have manually deleted the table.B'cos EF doesn't know anything about your manual operations hence __MigrationHistory table still exist your old migration details (i.e. manually deleted table's record).
In my case I used Ubuntu, EF 6 and the database was in the docker and it's doesn't updated DB.
I added --connection attribute and it's works, an example:
sudo dotnet ef database update --connection
"Server=localhost;Database=temp;User Id=sa;Password=xxxxxxx;"

Entity Framework code first - update database in production

I have enabled migrations. I am not using automatic migrations and I do not want to use them.
I have done 3 migrations.
In my development environment I am updating database via VS using the command
Update-Database -verbose -StartUpProjectName EntityFrameworkContext -TargetMigration <MigrationName>
In my devlopment environment, everything works correctly.
Now, I must update the database in production environment. I am using following command
Update-Database -verbose -StartUpProjectName EntityFrameworkContext -TargetMigration <MigrationName> -script
I run the generated script on production database. No error. The table __MigrationHistory looks to be good (I have just some doubt about the column Model that is different from dev environment). In this tabel I have the correct number of rows and the column MigrationId is correctly filled.
The database is exactly the same of the dev database. I have checked it.
I have updated also the program.
But, I do not understand why I still have always the same error:
The model backing the 'PublicAreaContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I am going crazy.
Thank you for your help

Why does EF Migrations insist on me enabling automatic migrations?

I am very, very new to using migrations, but based on the answer to the SO question Database is not getting created at first time, using the Powershell command Update-Database -Script should give me a script to execute outside of automatic migrations. Yet when I try running that command, I get an error message that says:
Unable to update database to match the current model because there are
pending changes and automatic migration is disabled
I would rather follow Chris Pratt's sage advice - in his answer to the linked question - and leave automatic migrations disabled, but the alternative he offers is insisting on automatic migrations.
I am trying to create the database from scratch, using the CreateDatabaseIfNotExists initializer.
It means there are changes to your current model that haven't been added to a migration.
Try:
Add-Migration YourMigrationName
Update-Database -Script
This will first create a migration with the updated model changes, then you can generate the update database SQL script.

Database has no tables but we are getting "No pending explicit migrations."?

We have entity framework migrations that create a few tables to setup an existing database. We ran the migrations once and they all ran but after looking at the database via SQL Server non of the tables that were supposed to be created were visible, even the Migration History table is not there.
We keep running the migrations again to see if we can create the tables but we keep getting the "No Pending Explicit Migrations" message.
Is there some other cache Entity Framework uses to figure out if Migrations have already run or not. How is it picking up that migrations have run yet the migration history table is not even there.
My Execution Call:
migrate.exe DllWithMigrations.dll /startUpConfigurationFile:"My Path\Web.config" /connectionProviderName:System.Data.SqlClient /connectionString:"My Connection String"