Generating MigrationHistory table in reverse engineered code first - c#

I have reverse engineered on existing database for code first. Next i Enabled-Migrating for the context (Code based migration). When i create an initial add-migration it works fine and would apply on an empty database.
But my requirement is that i need to use the same database i used for creating the models because of the data it has.
Now the conundrum is how do i implement the code based migrations. My database does not have a migration history table. So, when i run Update-database, it tries to create the existing tables and fails.
How can i capture the current state in the migration history or instruct EF to create the migration history with the current schema as the starting point.
Do i need to turn on the automatic migration for initial setup. Please suggest.
Note: I am using EF 6.

You need to establish a baseline migration of the existing items. So the first migration you create should be:
add-migration Initial -IgnoreChanges
The ignore changes tells EF to just save a snapshot of the current database. Now any subsequent migrations will not include the existing tables (just the changes). This would allow you to continue updating your existing database since EF will see the record in __MigrationHistory or deploy to a new, empty database.
See the under the hood section here.

Related

Adding EF Core Migrations to an existing database, while still enabling creation of the database from scratch

Last year, I rewrote a legacy application with .Net Core and EF Core, but elected not to add migrations at the time due to other limiting factors. The time has finally come where the new application can operate as the "single source of truth" for schema changes, but I'm at a bit of a loss as to the best way to move forward.
My end-goal is to have migrations that can scaffold out the entire existing database from nothing (minus the data contained within the non-lookup tables). Unfortunately, the most viable solution I've come up with so far is to build my migrations against a new, blank database. Then once the initial migration is created that matches the state of the current database, I would be able to copy over the __EFMigrationsHistory from the newly created database to the old one.
Alternatively, I can scaffold out a blank initial migration, and I could attempt to add logic in that migration to create the database from a SQL file if it did not exist.
Neither solution seems particularly "good". Aside from tools like FluentMigrator, are there any EF Core-centric approaches that can simplify creating migrations for an existing database that will need to be recreated for tests?
I had a similar issue when I wanted to squash all the existing migrations of the past 5 years (because it took forever to create a new instance). Here's how I did it:
Remove all migrations from your code, including any DbContextModelSnapshot.cs
Scaffold an initial migration: it will contain everything to create a new DB instance
Scaffold another migration, dedicated to seed the initial data (that's optional if you don't need to seed data on your newly created instance). The goal is to isolate the seed from the SQL structure.
Commit your changes
Keep the migrations, but remove the bodies of the Up and Down methods; the goal is to trick EF Core into thinking it applied those migrations
Update your existing instances with those empty migrations: nothing will be done, but the __EFMigrationsHistory table will contain them and ignore them in the future
Revert your changes, to restore the bodies of the migrations
With all those steps, you can now update your existing instances with any future migrations, yet also recreate new instances from scratch.

EF Core 3.1 DB First to Code First update old database

The project at the moment is using Database first approach, now we are switching to code first for various reasons.
using Scaffold-DbContext I have generated DbContext (we already have, but probably it will be less error prone) from one of dev environments where they are latest changes applied. Removed the copied .HasConstraintName(""); and .HasName(""); in .OnModelCreating() and I've created the Initial migration. So far so good.
The problem comes with updating existing database which is old compared to latest and as well keep the data.
What is the best way to update the database with the migrations?
I've added this in the Configure() method under Startup.cs to create the database if doesn't exists with the migrations, but not sure how to update old, existing one which doesn't have migration history table.
if (!context.Database.EnsureCreated())
context.Database.Migrate();
One solutions is to create an initial migration from your old database and put the MigrationId (example : 20200609075705_Initial ) manually into the dbo.EFMigrationHistoryTable.
After that you can add new migrations without any problem .

Database First - trying to recreate my entities that exist

I'm trying to connect my app to an existing Application.
So i created the Entities with the Entity Framework Database First.
It create all my entities and my Context that's fine.
But when i try to run it tell me that my migrations are not up-to-date so i tried to add-migration test to see what was missing...
It's creating all the table i asked it from DataBase First...
I cant recreate those tables i just want to be able to connect to those tables...
I absolutly need to connect to those tables, i cannot create a new one and i cannot clone the database.
How can i achieve this... i didnt find any resources on the subject that goes from the start to the end of the process.
Some help would be awesome!
The Problem: You can't reset migrations with existing tables in the database as EF wants to create the tables from scratch.
What to do:
Delete existing migrations from Migrations_History table.
Delete existing migrations from the Migrations Folder.
Run add-migration Reset. This will create a migration in your Migration folder that includes creating the tables (but it will not run it so it will not error out.)
You now need to create the initial row in the MigrationHistory table so EF has a snapshot of the current state. EF will do this if you apply a migration. However, you can't apply the migration that you just made as the tables already exist in your database. So go into the Migration and comment out all the code inside the "Up" method.
Now run update-database. It will apply the Migration (while not actually changing the database) and create a snapshot row in MigrationHistory.
You have now reset your migrations and may continue with normal migrations.

Entity Framework 6 Update-Database fails for migration created with -IgnoreChanges

I'm trying to create a DbContext specific to may Domain that has one model class entirely managed by EF, and another that gets mapped to a database view. To ensure EF doesn't try to create this view that already exists, I added just the view to my DbContext and ran the following command:
Add-Migration InitialUnmanaged -IngoreChanges
This creates a Migration with an empty Up and Down, which is exactly what I want. I'm able to update my dev database using this Migration, but whenever I try to add a second Migration that includes my EF-managed model class, I get an error.
Add-Migration Initial
Unable to generate an explicit migration because the following explicit migrations are pending: [201510151553565_InitialUnmanaged]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
The thing is, I've already applied that explicit Migration, and I can see it in my MigrationHistory table.
MigrationId
201510151553565_InitialUnmanaged
Can anyone help me understand why this is happening and how to work around it?
I figured this out.
When I applied the Migration, it put the Migration History table in the same default schema as the model. However, when I tried to roll it back, it was looking for the Migration History in the connected user's schema. Since it wasn't there, it thought the database was at version 0.
I created an OracleDbConfiguration class to specify a custom HistoryContext that specifies the default schema for the Migration History table and I'm able to rollback as expected after applying a Migration.
I verified that I was able to recreate my initial steps and have them work as expected now that I'm explicitly specifying the schema for the Migration History table.
Either delete the migration or just run Update-Database to put entity back in sync. If it is an empty migration your database will not change.

Merging migration entries in Entity Framework

I have an Entity Framework 6 CF project that has a few migrations already in place.
The model is now stable and there is no need to keep the migration history that already exists.
Is there a way to reset the model and merge all migration commands into the initial migration?
As an example, the first migration adds a column while the second migration adds a unique, non-clustered index. I now want to see all these changes directly in OnModelCreating rather than in separate migrations.
Migrations have both an Up and Down. You can always Re-Scaffold your application by tearing the migrations down and then adding a new migration. The Down process does not change your model, only the changes to the database. Use Update-Database -Target:migrationTargetName or Update-Database -TargetMigration:migrationNumber.
If you want a migration which starts with no database and ends with your current model, you can tear all the migrations down with Update-Database -TargetMigration:0. It's a good idea to tear down the database and then run Update-Database as a test to verify the database changes are all in sync.
Bear in mind, if you tear your migrations down to 0 and then run an Add-Migration, you will want to look very closely at the generated scaffold, as it will likely be drastically different than the incremental changes.

Categories

Resources