Add Migration for Existing Table with Entity Framework - entity-framework

I am in a situation where we have been using (code first) EF migrations against a database that is used as the backing store for two applications. Over the past year or so, we have successfully made DB changes via migrations.
However, at some point a few tables seem to have been manually added and we are now experiencing FK reference errors when we try to delete.
I have attempted the obvious, with the obvious result: Adding the models and generating a migration is going to attempt to recreate the tables in the database.
Is there a strategy to add these new tables to our data model and get our migrations up to date?

Related

In EFCore, how do I scaffold my context and then start doing migrations?

I want to do code first development on an existing SQL Server Database. I have used the Scaffold-DbContext command to generate the entities that I want into the tables I want. That's great. But, there were previously code first migrations done to this database. So I deleted the __EFMigrationsHistory table in the SQL Database. Now I want to start doing migrations. Unfortunately, when I run Add-Migration, it generates migration code to generate all of the tables again. I don't understand how I am supposed to tell it that these tables already exist. When I am reverse engineering, how do I generate the migration of the stuff it's scaffolding for me in the existing database?
Code First Migrations uses a snapshot of the model stored in the most recent migration to detect changes to the model (you can find detailed information about this in Code First Migrations in Team Environments).
Source here.
Run Add-Migration InitialCreate –IgnoreChanges to create the initial migration from an existing database. Then update-database to simply add the migration to the _EFMigrationsHistory table.
After that, you are good to go brother.

How EF detect model changes without migration history table

I am using entity framework code first migrations. Very first time I do not have migrations enabled. When I run the project it creates _migrationhistory table with one row in it.
Then I delete this table and ran application, it ran successfully. Now I add one more property to entity and try to run but it did not run complaining that model is not compatible with database.
My question is how EF and database knows model is changed or database is different than model without _migrationhistory table or migrations in code?
Entity framework first checks if the database has _migration history table. If it doesn't have one, it tries to create one and run all the migrations from the beginning and also inserts the migrations name as a record in the migration history table.
Because, you have deleted the migration history table, entity framework cannot compare its migration records with the migration files. Therefore, it tries to run all the migrations again. But, this database already has the table for the relevant entities. Therefore, an error message (model is not compatible with the database) is displayed to the user.

How do you rename an Entity Framework database after it has been created?

I am using EF 6 code first. As part of the code-based migration, I would like to rename the existing database after applying all the pending migrations. Can this be done?
I don't think this would be (easily?) possible (without causing errors)
If you rename the database during the migration it wont be able to write the migration out to the migrationhistory table as the connection string will still be pointing to the old database.
Perhaps a better option would be to build something into the system to rename the database and adjust the required configuration outside of EF entirely.

Why do Entity Framework Migrations store the whole model and not a hash in the __MigrationHistory table?

Code First Entity Framework, from versions 5 - 6.1.1+, with migrations enabled stores database updates as "migration" classes. Each class has an accompanying resource file containing a serialized version of the model, i.e. the entities, properties, relationships, etc.
This serialized version of the model is then stored in the database in the __MigrationHistory table with a single row per migration. The information in this table is used to check what model version a database is at and thus what migrations still need to be run. It is also used during some database initialization strategies to determine if the running code's model matches the last migration deployed to that database.
In neither of the use cases for the __MigrationHistory table is the fully serialized model needed. At best only a hash of the model would appear to be required.
As we've had our code first database running for a while, the __MigrationHistory table is storing 36K per row for a total of 4MB. This isn't huge but seems unnecessary.
So the question: Why doesn't Entity Framework store a hash of the model in the __MigrationHistory table?
When you changing your model and adding a new migration, EF migrations generates Up and Down methods for you. And these changes comes from comparing full model from previous migration to your actual model.

EF Migrations - straight to final schema

My schema has evolved over many iterations. I have a set of migrations taking the schema from an empty db to one with dozens of tables and scores of columns.
Along the way there have been several additions of tables, columns and constraints, sometimes followed (in light of experience or new knowledge or changes in the spec) by removal or alterations. Sometimes a table or column name has been re-used or re-purposed.
Now, EF migrations seems perfectly able to run through the sequence creating, altering, dropping, creating again, altering, etc., to get to the latest schema, but it feels wrong. In an extreme case there might be dozens of migrations creating tables followed by dozens more dropping tables until the final schema might be one or two tables (unlikely, I know). An option to go from scratch to just those final tables would feel right.
In my Ruby days with ActiveRecord migrations there was an option to build only the final schema, without stepping through and possibly undoing or redoing work along the way. Of course this meant keeping a complete DDL version of the schema up to date after each migration, but somehow it felt more elegant.
Has anyone done anything similar with Entity Framework?
You might like to try deleting the __MigrationHistory table from your database, removing the Migrations folder (backing up your Configuration.cs file), and then enabling migrations again.
Then start here for PM commands to build scripts
Generate full SQL script from EF 5 Code First Migrations
from code, there is an option on the ObjectContext not directly on DbContext
string script = (context as IObjectContextAdapter).ObjectContext.CreateDatabaseScript();
Of course Automated Migrations would work if you dont need to see the magic and have altered the generated scripts.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourDbContext,
YourMigrationConfiguration>()
Context.Database.Initialize(true);
And if it is an EmptyDb Schema, EF will do that for free.
Context.Database.Initialize(true);