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
Related
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
How do you get EF back in Sync with code without losing data when Update-database returns the following message
Error Message: System.Data.SqlClient.SqlException (0x80131904): There
is already an object named '' in the database.
I originally wrote this as a self-answering question as I had struggled with the proble for some time, as had a few colleagues, but unfortunately, my answer was deleted and I can't recover it.
Since it's a situation that I suspect can happen several times as people try to "clean up" old migrations, I thought I'd document it with step by step instructions.
Description of the situation we found ourselves in:
We couldn't can't create a new local database because the init script was incomplete, and couldn't apply updates to the production database because the migration scripts create tables that already exist. And, we didn't want to delete production data.
Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.
Error Message: System.Data.SqlClient.SqlException (0x80131904): There
is already an object named '' in the database.
Problem Background:
To understand this in more detail, I'd recommend watching both videos referenced here:
https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx
To summarise, EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.
Solution: What we need to do is to trick EF into thinking that the current database is up to date, while "not" applying these CreateTable commands since the production database already exists. Once production DB is set, we still need to be able to create local databases as well.
Step 1: Production DB clean
First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts.
Open your production database and delete/drop the dbo.__MigrationHistory table.
Step 2: Local environment clean
Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.
Step 3: Recreate Initial
In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts).
Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code.
If you had any seed operations in the previous Configuration.cs, then copy that across.
Step 4: Trick EF
At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.
Step 5: Update-Database
With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like.
Now, uncomment that code and save.
You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.
Step 6: Confirm EF is ACTUALLY up to date
If you had code that hadn't yet had migrations applied to it, this is what I did...
Run "Add-Migration MissingMigrations"
This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.
Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.
Step 7: Re-confirm and commit.
Build, test, run. Ensure that everything is running then commit the changes.
Step 8: Let the rest of your team know how to proceed.
When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.
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.
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.
I started off my project by using Entity Framework Code First. When I was ready I uploaded my database and code to my host provider. Everything worked.
I need to add a new field to one of my classes and I don't want to loose the data in the database. Thus, I tried following some blog posts about using Code First Migrations. I did the following:
I backed up my remote (production) database.
I attached this database locally
I added the property to my class
PM> Enable-Migrations
PM> Add-Migration AddSortOrderToCar
PM> Update-Database
At this point I created a .bak file of the local database and then used that file to 'restore' to the remote one.
Lastly, I published the code to the remote site.
When I visit the site I get the following error message:
The model backing the 'blahblah' context has changed since the database was created. Consider using Code First Migrations to update the database.
What am I doing wrong?
From my experience that suggests that migration table is out of sync (even if your data isn't), and that's been part of the db schema now (since 4.3 I think - under system tables).
There could be many reasons and ways to experience that error , but most of the time...
The problematic part is some combination of manually backing/restoring the full database with code changes alongside - I'm not entirely certain as to why always.
In short, even if Db-s are the same migration table data might not be - and hash comparison may fail (still full restore sounds like good enough - but you have 'two sides').
What works for me is to use
Update-Database -Script
That creates a script with a 'migration difference',
which you can manually apply as an SQL script on the target server database (and you should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...
Remove the migration table (target - under system tables) - as per http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx comments in there - that should fail back to previous behavior and if you're certain that your Db-s are the same - it's just going to 'trust you',
As a last resort I used - make a Update-Database -Script of the full schema (e.g. by initializing an empty db which should force a 'full script'),
find the INSERT INTO [__MigrationHistory] records,
just run those, insert them into the database,
and make sure that your databases - and code match,
that should make things run in sync again.
(disclaimer: this is not a bullet proof to work at all times, you may need to try a few things given your local scenarios - but should get you in sync)
I think in step 6 you need to run Update-Database -Verbose
Also this link is very helpful for updating database in EF with Scaffolding
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-entity-framework-scaffolding-and-migrations