I'm using EF 6.0 for my project in C# with manual migrations and updates. I have about 5 migrations on the database, but I realised that the last migration was bad and I don't want it. I know that I can rollback to a previous migration, but when I add a new (fixed) migration and run Update-Database, even the bad migration is applied.
I was trying to rollback to the previous migration and delete the file with bad migration. But then, when I try to add new migration, I get error when updating database, because the migration file is corrupted (more specifically, first line of code rename the table A to B and is next lines, EF is trying to update table with name A - maybe it is some EF bug).
Is there some query I can run, which would tell EF something like "Forget last migration like it never existed, it was bad"? Something like Remove-Migration.
Edit1
I found solution suited for me. Changing model to the good state and run Add-Migration TheBadMigration -Force. This will re-scaffold the last, not applied migration.
Anyway, this still not answer the original question completely. If I UpdateDatabase to the bad migration, I did not found good way how to rollback and create new migration, excluding the bad one.
Thanks
You have 2 options:
You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version.
I use this option on things that have gone to multiple environments.
The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version.
Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration
I use this option while developing.
As the question indicates this applies to a migration in a development type environment that has not yet been released.
This issue can be solved in these steps:
Restore your database to the last good migration.
Delete the bad migration from your Entity Framework project.
Generate a new migration and apply it to the database.
Note: Entity Framework and Entity Framework Core use slightly different command names
Step 1: Restore to a previous migration
If you haven't yet applied your migration you can skip this part. To restore your database schema to a previous point issue the Update-Database command with -TargetMigration option to specify the last good migration. For EFCore use Update-Database "Name-of-Migration"
If your entity framework code resides in a different project in your solution, you may need to use the '-Project' option or switch the default project in the package manager console.
Update-Database –TargetMigration: <name of last good migration>
For EFCore:
Update-Database <name of last good migration>
To get the name of the last good migration use the 'Get-Migrations' command to retrieve a list of the migration names that have been applied to your database, use 'Get-Migration' without the 's' if you are using EFCore.
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 most recent applied migrations first. Pick the migration that occurs in the list after the one you want to downgrade to, ie the one applied before the one you want to downgrade. Now issue an Update-Database.
Update-Database –TargetMigration: "<the migration applied before it>"
For EFCore:
Update-Database "<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.
EF will reject the command if your downgrade might cause data loss. Use the '-Force' option to accept the data loss and allow the command to execute.
Step 2: Delete your migration from the project
If you are using Entity Framework Core you can use the 'remove-migration' command, for Entity Framework, delete the files of the unwanted migration in your EF project 'Migrations' folder manually. At this point, you are free to create a new migration and apply it to the database.
For EFCore:
remove-migration name_of_bad_migration
Step 3: Add your new migration
add-migration my_new_migration
Step 4: Apply your migration to the database
update-database
For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (#DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):
Update-Database <Name of last good migration>
Remove-Migration
For example, in my current development the command became
PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM>
The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.
There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:
PM> get-help entityframework
Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)
Initially I tried Remove-Migration by itself and found the error command confusing:
System.InvalidOperationException: The migration '...' has already been
applied to the database. Unapply it and try again. If the migration
has been applied to other databases, consider reverting its changes
using a new migration.
There are already suggestions on improving this wording, but I'd like the error to say something like this:
Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will
unapply all migrations that occurred after the migration specified to
Update-Database. You may then run Remove-Migration (migration name to remove)
Output from the EF Core help command follows:
PM> get-help entityframework
_/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\
TOPIC
about_EntityFrameworkCore
SHORT DESCRIPTION
Provides information about Entity Framework Core commands.
LONG DESCRIPTION
This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.
The following Entity Framework cmdlets are included.
Cmdlet Description
-------------------------- ---------------------------------------------------
Add-Migration Adds a new migration.
Remove-Migration Removes the last migration.
Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database.
Script-Migration Generates a SQL script from migrations.
Update-Database Updates the database to a specified migration.
Use-DbContext Sets the default DbContext to use.
SEE ALSO
Add-Migration
Remove-Migration
Scaffold-DbContext
Script-Migration
Update-Database
Use-DbContext
You can also use
Remove-Migration -Force
This will revert and remove the last applied migration
I am using EF Core with ASP.NET Core V2.2.6. #Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.
So, For those using EF Core with ASP.NET Core V2.2.6 +...
instead of
Update-Database <Name of last good migration>
I had to use:
dotnet ef database update <Name of last good migration>
And instead of
Remove-Migration
I had to use:
dotnet ef migrations remove
For --help i had to use :
dotnet ef migrations --help
Usage: dotnet ef migrations [options] [command]
Options:
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
Commands:
add Adds a new migration.
list Lists available migrations.
remove Removes the last migration.
script Generates a SQL script from migrations.
Use "migrations [command] --help" for more information about a command.
This let me role back to the stage where my DB worked as expected, and start from beginning.
First, Update your last perfect migration via this command :
Update-Database –TargetMigration
Example:
Update-Database -20180906131107_xxxx_xxxx
And, then delete your unused migration manually.
As of .NET Core 2.2, TargetMigration seems to be gone:
get-help Update-Database
NAME
Update-Database
SYNOPSIS
Updates the database to a specified migration.
SYNTAX
Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]
DESCRIPTION
Updates the database to a specified migration.
RELATED LINKS
Script-Migration
about_EntityFrameworkCore
REMARKS
To see the examples, type: "get-help Update-Database -examples".
For more information, type: "get-help Update-Database -detailed".
For technical information, type: "get-help Update-Database -full".
For online help, type: "get-help Update-Database -online"
So this works for me now:
Update-Database -Migration 20180906131107_xxxx_xxxx
As well as (no -Migration switch):
Update-Database 20180906131107_xxxx_xxxx
On an added note, you can no longer cleanly delete migration folders without putting your Model Snapshot out of sync. So if you learn this the hard way and wind up with an empty migration where you know there should be changes, you can run (no switches needed for the last migration):
Remove-migration
It will clean up the mess and put you back where you need to be, even though the last migration folder was deleted manually.
For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.
$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force
Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.
Be sure you don´t have error in project files, even in your migration files, I had an error in my last migration file and did not allow me remove it.
I'm using Visual Studio 15.8.5 with Sql Server Data Tools 15.1.
I've created an SQL Server database project and imported the schema of an already existing database. I've made several minor changes to a few tables of the database and published the updates to the development database without any problems.
After adding a few SQL scripts to the project, all of them with:
Build Action = None
publish fails, despite no changes have been made in any of the database objects of the project.
This is the part of the auto-generated publish script that causes the problem:
/*
The table [lut].[KAE] is being dropped and re-created since all
non-computed columns within the table have been redefined.
*/
IF EXISTS (select top 1 1 from [lut].[KAE])
RAISERROR (N'Rows were detected. The schema update is terminating
because data loss might occur.', 16, 127) WITH NOWAIT
GO
Table [lut].[KAE] has not been changed, though. One of the scripts is redefining its schema but this should make no difference since this is a 'No Build' script.
What am I possibly doing wrong here?
Edit:
I've done a schema comparison as #MadBert advised. I originally used my actual database as source and my sql server visual studio project as target. No differences were found.
I then switched source and target databases and compared again. The following 'difference' was detected.
As you can see this is not an actual difference, it looks like a Visual Studio bug in schema comparison. Any ideas on how I could circumvent this behavior?
It turned out that a refactor log file was the culprit.
I tried to publish to an empty database, as #Ogglas wisely advised. I noticed that during publish I was getting the following message:
The following operation was generated from a refactoring log file
8e659d92-10bb-4ce9-xxxx-xxxxxxxxx Rename [lut].[KAE].[xxxxx] to
$$$$$$$$$ Caution: Changing any part of an object name could
break scripts and stored procedures.
I then noticed that my SQL Server Database project contained a .refactorlog file
It seems that this log file was generated after I changed the offending table schema. The schema of the table was later reverted to its original state but the log file remained.
I deleted this log file and after that publish finally succeeded!
Had a similar problem when a SQL Server Database project was set to the wrong Target platform. Edit this in project properties to match the target server. Initiate a schema compare again by right clicking on the project and select Schema Compare....
Also check if Ignore whitespace is marked in Schema Compare Options. If you still have a difference one way or another try pasting the text in Notepad++ with Show All Characters on and see if you can spot a difference.
If you still can't find any difference, try creating a new database from the project and use SSMS GUI to compare. Does the table have the same Lock Escalation settings etc?
I created the Models of my database on VS for Mac and used terminal for create migrations:
dotnet ef migrations add IntitialMigration
Then, I updated my database:
dotnet ef database update
But after I changed my Models and I created another migration:
dotnet ef migrations add SecondMigration
And tried to update the database:
dotnet ef database update SecondMigration
I received the following error:
There is already an object named 'Emails' in the database.
I've searched and I found a probably solution:
Add-Migration SecondMigration -IgnoreChanges
But this only works at PMC on Windows. I'm using VS for Mac and all the commands are typed on Terminal. Does anybody know how to update a database using Migrations after change the Models?
I found the solution. It seems that on VS 2017 for Windows, when you add a Migration, it is automatically added on the solution. But, on VS for Mac, that doesn't happen. You need to manually add the each new migration to the solution. I created the InitialMigration migration and update it to the database. For some reason I don't know why, I removed the migration from the solution and I created the new SecondMigration migration. That's the reason that all the tables that were on InitialMigration were on SecondMigration too.
If you just run update database it will also try to update with previous migration. (which is why its complains about adding whats already there). You can run an update just for one single migration by adding the name of the migration you want to run after the command.
May be this question seems duplicate. But here are the issue that I am facing with the command.
If I run this command,
update-database -force
the first error I gets..
There is already an object named tblAbc in the database
Then I googled and everytime I get a stackoverflow link for suggesting to run
Add-Migration Initial -IgnoreChanges
If I run this command and then run the update command, No error - Running seed method
But it doesn't sync the database with the new updates
Then I tried for number of times but same issue, hence I looked for some alternate solution & I got.
to use update-database -Script but if I run this command and get the following error.
User canceld Save dialog box
Then I tried to fix this by opening SQL Managment Studio and
Tools>>Options>>designers>> unchecked the Prevent saving changes that required table recreation
But after this also same error message.
Then I tried to add the following coniguration in my context class
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion <context, Configuration>());
It ran with success and Running Seed method but it doesn't sync the latest updates.
Using an Existing Database
Depending on the state of your context you need to the one of the following...
IF YOUR DATABASE CONTEXT CONTAINS ONLY YOUR EXISTING TABLES AND NO CUSTOM CHANGES DO THE FOLLOWING
Add-Migration Initial -IgnoreChanges
This will create a blank migration script
update-database
This will update the database to this migration but no changes will be applied. You can now add your changes to the database context. After you have finished do the following
Add-Migration Custom
This will generate a migration script with your changes in it. Then update your database again.
update-database
IF YOUR DATABASE CONTEXT CONTAINS YOUR EXISTING TABLES AND ALSO YOUR CUSTOM CHANGES
Add-migration Initial
This generates a migration script. Go through the migration script and remove any references to existing tables in both the UP and DOWN methods. You will be left with a script which only includes your custom logic.
update-database
Hope this helps!
Update the migration file with the type, size and maxLength.
Example:
maxLength: 50,
type: "varchar(50)",
Properties:
I am trying to do a rollback with South in my django app. I am getting this message when I run my command: DatabaseError: table "forms_logo_version" does not exist. This is the command I'm running python manage.py migrate myformsapp 0044.
I've checked the DB and the table does not exist, but why is this a problem? If I am deleting the table anyway, why is this throwing an error? Is there anyway I force the script to continue?
I have simply created a blank table in the database and the script ran fine after that. I would still like to know the answer to my questions above.
You can find in your migrations file 0044_*.py method named backwards and remove line with something similar to db.delete_table('forms_logo_version'). If you do this makes some tests.
Connect to empty db and make forward migration and backwards, to be sure your changes don't affect another migration file.
I recommend you to figure it out why this table is missing from db? Probably South create this table (look into migrations) and only South should remove it.