Updating prod database after reverting and adding migrations in dev - entity-framework-core

I'm running an asp.net core app with ef core and two environments: prod and dev. I created some migrations and applied them to both environments a while ago, but needed to roll them back in development. After I rolled back in dev, I kept developing and now have many migrations in dev that are not in prod, as well as the reverted migrations in prod that I haven't rolled back yet. So now my environment's migrations look like this:
Prod => a,b,c,d
Dev => a,b,e,f,g
(one major thing to note: the migrations i'm reverting in prod (c,d)
are not being used, they were just models I created for
future use - that I ended up changing - so loss of data from these
migrations is not a concern)
I can't run the same commands I ran initially in dev since i'm not adding any migrations now, I just need to update the prod database to the migrations I have locally.
If I update-database b then update-database will this revert the changes in prod then update to my local migrations? Or will this revert the migrations i've added in visual studio? What are my options here?

On the production environment run a downgrade to the latest working migration:
Update-Database –Migration b
Then delete the 2 migrations c and d from your migration folder.
Finally you can update to the latest migration on the production enviroment:
Update-Database

Related

Manage Sqitch migrations when deploying different branches

When we deploy to our Testing environment with Sqitch, the migrations run and all is well. However, when we have to test a different code branch, the Sqitch migrations aren't rolled back. What I'm looking for is an idea of how others are solving this problem. For example, if I have a migration that creates a table my_table, and then deploy a migration from a different branch, Sqitch gets too confused to move forward.
Reason for branch change: we have features using our develop branch, and hotfixes being applied to master (I know; we're going to change that). Swapping over to test a hotfix caused all of this mess.
We considered having a Jenkins job to run a sqitch revert and have the user supply the migration to roll back to, but we want to eliminate the manual step.
How do you manage migrations when having to switch code branches?
I believe this is the purpose of sqitch-checkout

EntityFramework 7 RC1

Right now I have 2 environment.
Dev
Uat
In my Uat environment, I have deploy v0.1 migrations.
In my dev I have v0.5 migrations.
How to generate the script migration from v0.2 -> v0.5 ONLY
dnx ef migrations script
the above will generate the whole database script, which I only need to migration different.
How to rollback my database from v0.5 to v0.2?

How do you perform a rollback when using MigrateDatabaseToLatestVersion

With EF Migrations you can add migration scaffoldings and then keep running 'Update-Database' to apply changes. And in order to rollback the following works:
Update-Database -TargetMigration: <xyzMigration>
This is great for updating your dev. DB. However when I automate migrations using MigrateDatabaseToLatestVersion for deploying to other environments like test and prod. adding migration files for any changes and having them reflect works well.
But, in case I wanted to rollback to a specific migration how do I achieve that? 'Update-Database -TargetMigration:' only updates your local dev. DB or whatever your connection string is pointing to locally. And that has to be run via Package Manager Console. Is rollback not an option for actual deployments? Do you have to just 'Add-Migration' and specifiy a new migration that has all the changes you want reflected?
For a production database doing an Add-Migration with the changes you want would probably make the most sense, especially if you have multiple deployments.
Other options include:
Using DbMigrator.Update() with a parameter that indicates the target migration. (I'd probably use a separate build, just for this purpose...seems tricky to handle...especially when you add additional migrations in the future).
Update-Database also has optional arguments for -ConnectionString, but that would require setting up Visual Studio on a machine with access to the database you're targeting.

Code first deploy on production

I have copy of prod DB and code on my DEV PC.
On production I saw in system tables that 8 migrations records exist in _MigrationHistory. (The first version of the code and deploy was written by another person).
I need to add few new tables and code for work with them - models and controller. I can add new models for new tables and code for controller.
On the DEV PC I can start command
add-migration myNewMigration
and
update-database with option "-script"
and without it to get tables in my DEV DB and script to execute on Production.
For deploy I need to copy content on bin folder and new views on Prod and to run SQL script to create new tables in DB.
I was wondering is that enough because at the moment I see records for all migrations in my DEV environment corresponding records in Production environment in system tables - _MigrationHistory.
If I only run the SQL script on PROD may be new record for this operation will not appear in _MigrationHistory. So could be that a reason to get error that model is different and to have any problem after deploy.
Before making changes to the production database, ensure you have a complete backup.
I was wondering is that enough because at the moment I see records for all migrations in my Dev environment corresponding records in Production environment in system tables - _MigrationHistory
If you ran the code in your development environment, it will apply your explicit migrations.
If I understand your comment correctly, you see the same migrations in DEV and in PROD. If that is accurate, then PROD may be up-to-date.
Look in your Migrations folder in your project. There you will see a complete list of migrations, each one in its own .cs file (plus related .Designer.cs and .resx files). Compare what you see there to the list of migrations in __MigrationHistory in DEV and in PROD to understand the full set of migrations, and where they have been applied.
If I only run sql script on Prod may be new record for this operation will not appear in _MigrationHistory
Have a look at your migration scripts. They insert the appropriate entry into __MigrationHistory where they are run (including in production). Here's an edited example from one of my projects:
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201409082209285_VDisposer', N'Survey.Model.Migrations.MembershipConfiguration.MembershipConfiguration', 0x1F8B0800000...1A0200 , N'6.1.1-30610')
So could be that a reason to get error that model is different and to have any problem after deploy
If you are having an error that the model does not match the database, there is another reason.
Here's what I suggest to narrow down the differences:
Backup your production database.
Restore it in your DEV environment (use a name different than your usual DEV database, or backup your DEV database first. If using a different name, remember to temporarily change web.config to the new database).
Create a new migration.
Look at the code generated for the new migration. It will point out differences between what is in PROD and the state that DEV is in.
Remember to undo changes to your web.config after you are done.

Consolidating EF migrations into new InitialCreate

I have been using EF migrations for some time now and have more than 100 migration files in my project. I would like to consolidate these into a single migration before moving forward - ie I want to replace the existing InitialCreate migration with a new version that takes all my subsequent changes into account so I can then delete all the other migration files.
I do this very easily if I am not concerned with losing all the data in the DB, but I am.
How can I achieve this whilst keeping all data intact and also retaining the ability to recreate the database from scratch (without data) by just running Update-Database (which I believe is not possible using the approach outlined by Julie Lerman)?
Consider reading this nice article from Rick Strahl :
https://weblog.west-wind.com/posts/2016/jan/13/resetting-entity-framework-migrations-to-a-clean-slate
Basically the solution is not trivial and needs more than just reseting all the migrations into one
because you have two scenarios that needs to fit in ONE migration class:
Create a new database => the migration class should contain every table creation
My database is already up to date => I need an empty migration class
Solution:
The idea of this process is basically this: The database and the EF schema are up to date and just the way you want it, so we are going to remove the existing migrations and create a new initial migration.
In summary, the steps to do this are:
Remove the _MigrationHistory table from the Database
Remove the individual migration files in your project's Migrations folder
Enable-Migrations in Package Manager Console
Add-migration Initial in PMC
Comment out the code inside of the Up method in the Initial Migration
Update-database in PMC (does nothing but creates Migration
Entry) Remove comments in the Initial method You've now essentially
reset the schema to the latest version.
once the commented out migration has been executed on the desired database, uncomment the migration code
If you're not concerned with keeping this migrations, what I've done is delete everything in your migrations folder, and then target a new database in the connection string (or pass in a new one). After that, you can just run the add-migration command:
add-migration InitialCreate
And it should create the migration for you.
Below procedure has the benefit of working without doing anything with the DBs, __MigrationHistory can stay as-is. Also it will work if you have multiple different environments with different versions of the structure - provided you have the branches to match.
I turn the last migration into an initial migration. The trick is to use the oldest version of the code and DB that is in use, replace its last migration with a new initial migration and delete all previous migrations. Newer branches keep the more recent migrations so those will still work after merging to older branches.
So start in the OLDEST branch - PROD, normally - and do:
Remove all but the last migration
Remove the migration code in both the "Up" and "Down" methods in the last migration
Change build action of the last migration to "None" to let EF ignore it
Change active connection to point to a local DB database.
Make sure this local DB database does not exist
add-migration Initial
Copy Up and Down code from the created "Initial" migration to the last migration
Delete Initial migration
Change build action of the last migration back to "Compile"
Check in
Merge changes up
Test in DEV branch on LocalDB DB - it should do the new initial migration as well as the subsequent ones with no issues
Test in main branch on the latest DB - it shouldn't do anything
Note above only works if you don't add stuff to the migrations that EF doesn't do itself. E.g. if you add DB views etc. than the newly created migration won't get those, it only gets the scripts EF generates based on your code.
Removing all migrations or regenerating them has drawbacks so we took an approach we merged all older migrations.
It require a bit of scripting. You read about the details here https://www.bokio.se/engineering-blog/how-to-squash-ef-core-migrations/ and see the scripts here https://github.com/bokio/EFCoreTools/tree/main/MigrationSquasher
The basic is the following steps though (copied from the blog post):
Overview of our approach
Create a new fresh database from the old migrations (We will use
this for comparison later)
Find a suitable target migration to be
the new initial (We picked one about 3 months old)
Write a script to
merge the Up() methods of all earlier migrations into the Up()
method of a new migration. We ignored Down() because we don't use it
for old migrations.
Generate this migration and add it to the
project. In our case we called it
20200730130157_SquashedMigrations1.cs. We used the snapshot from the
target migration we had picked.
Generate a 2nd prep migration that
inserts into the migrations history that
20200730130157_SquashedMigrations1.cs has already run. We called
this 20200730130156_SquashedMigrations1_prep.cs. Note the slightly
smaller timestamp on that one to make sure it runs before the real
migrations.
Delete the old migrations
Point our config to a new
database and run the migrations.
Compare that the schema we generate
is equal using the Sql Schema Compare in Visual Studio.
Work through
the issues until we have equal schemas. This part is a bit
complicated but I will get back to it.
Merge and 🤞 (Ok, we did run
more tests both on local and staging databases)
I hope this helps someone else. The EF team is looking at improving this story so if you have feedback on your requirements it probably help them to post that now https://github.com/dotnet/efcore/issues/2174.
We had the same problem.
The general solution we found was to
Archive the old migration / context on a Nuget Package (including dependancies and with a different namespace to avoid conflicts)
Delete all migrations and create a new Init (InitV2) Migration from scratch.
Change the startup sequence of our application:
If the database contains the first old Init migration then
Migrate the database using the Nuget Package to be sure it will be up to date
Then erase the content of the __EFMigrationHistory table and Insert the new migration in the table
After that use the standard Migrate method on the new context
That's it !
This solution is relatively simple. It solve all cases
New database (will be using the InitV2)
Old Database (will be upgrading to the last V1 Migration and after that to the last version of the v2 Database)
Be aware, if you used custom scripts/sql(...) in the v1 migrations, you have to check if the v2 Init migrations needs it.
To be sure it was OK, we created an empty database from v1 migrations and another one from v2 init migration and did a schema and data diff (with Visual Studio SQL Server Tools)