EF7 Exclude Class/DbSet From Add Migration Operation - entity-framework-migrations

(Version 7.0.0-beta5)
Is there a way to exclude a class or DbSet from being included in the migration add command evaluation?
The database I'm building will include some tables that are replicated from another environment. They need to be included in the DbContext so they can be queried and joined, but should never have migrations generated for them.
What's the best practice in this situation?

As of beta6, what works best for me is ensuring that the DbContextModelSnapshot includes mappings for the replicated entities.
Once the entities are mapped the migration scaffolding process compares the model snapshot to the entities to determine if there are changes. Since the entity classes match the model snapshot, no migrations are generated relating to those entities. When the DbContextModelSnapshot is regenerated and overwritten, it keeps the same mappings because there were no changes.
Also in the future there may be a feature to help out with this, as seen in this issue - no promises though, and not for the first release.
https://github.com/aspnet/EntityFramework/issues/2725

You can manually remove the creations or alterations from the migration file.

Related

EF6 Updating Code First Model from the Database

I inherited an ASP.NET MVC application using Entity Framework 6.2. The application was originally built using Code First and I can see migrations that have been applied to the database. The structure of the database seems accurate.
However, a ton of relationships have been added to fix referential integrity issues and these were done directly on the database. There are a bunch of them. Can someone help me to update the models from the database in a code first implementation? Ideally it would remain code first, not a conversion, but I need to do a one time update.
I'm more familiar with newer EF Core and I thought it would as easy as running a scaffold-dbcontext command with a -force and some cleanup. But no such luck in this older version. Is there something similar?
Depending on what a 'ton' means and whether you need to keep the old migrations you could either just rebuild the entire model by doing code first from existing database or you could save the generated code into a folder and do a manual reconstruction:
Run code first from existing database into a new folder.
Map new fields and navigation properties into existing models.
Fix up any fluent code (modelBuilder).
Generate a migration which should include those changes.
A good test would be restoring a pre-change version of the database and running the migration against it. Then perhaps use a schema compare utility.
Apply the migration to databases. If the database already includes the changes, comment out the Up() code before applying. This will update the stored model so the next migration does not repeat these changes.

Generating Entity Pocos from Existing Database

Using code-first, is there a way to generate entity classes from an existing database? I get how to use migrations. I get how to update a database with migrations. What I don't know is how to create a model set from an existing database that was created before migrations was a thing. I have a lot of tables.
What is the appropriate work flow here? I would really rather not write these by hand.
NOTE: I CANNOT USE AN EDMX. So do not register this as a duplicate of the thousand questions that say "just create an edmx file."
I'm moving a major legacy project over using Code First to an existing database. https://msdn.microsoft.com/en-us/data/jj200620.aspx. First thing I did was modify the default templates so I minimize the changes needed to namespace, etc. (I move the classes to other project after generating them). https://msdn.microsoft.com/en-us/data/jj593170.aspx Then I reverse engineer in small groups of related tables, create a migration, verify everything in the Up() code matches my database, comment the Up() code out and update the database. You could also add a migration with -IgnoreChanges, but I like to see the code. After a while I roll all the little migrations into a single migration using this technique http://cpratt.co/migrating-production-database-with-entity-framework-code-first/#at_pco=smlwn-1.0&at_si=54ad5c7b61c48943&at_ab=per-12&at_pos=0&at_tot=1.
Some of the referenced links mention EF Power Tools, but I don't believe I needed to install those to reverse engineer (VS 2013, EF 6.1.2). I did need to install this Nuget package for the templates: https://www.nuget.org/packages/EntityFramework.CodeTemplates.CSharp/

Issue with entity framework migration. [Unable to generate an explicit migration because the following explicit migrations are pending]

I am using EF code first and asp.net MVC. Here is my technical stack.
Visual Studio 2010
Entity Framework 4.3.1
In my migrations folder, I can see three migrations files are existing.
InitialCreate
AddStandardException
DocumentScope
When I check my database I can see that _MigrationHistory table has all three migrations applied. Now I have added one more DbSet, and I want to write migrations for it. When I attempt to give this command
Add-Migration NewTable
It gives me this error :
Unable to generate an explicit migration because the following explicit migrations are pending: [201402121621095_AddStandardException, 201402190713571_DocumentScope]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
I don't understand why is it complaining about pending migrations whereas all migrations have been applied?
How do I even troubleshoot this ? I tried with -Debug switch but no luck.
I found a workaround to it. I have just commented code inside the Up() and Down() functions. Then ran Update-Database. It applied some dummy migrations and then reported that
Unable to update database to match the current model because there are
pending changes and automatic migration is disabled. Either write the
pending model changes to a code-based migration or enable automatic
migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to
true to enable automatic migration.
After this when i ran
Add-Migration NewTable
It gave me the correct result. Any idea whats going on here ?
You either need to run "update-database" from the package manager console to push your changes to the database OR you can delete the pending migration file ([201402121621095_AddStandardException]) from your Migrations folder and then re-run "add-migration" to create a brand new migration based off of your edits.
Explanation: "update-database" basically modifies existing table fields while "add-migration" works like git by making a snapshot of the distinct model changes. These snapshots show how the database evolved over time so they are more useful to your code user than the EF or the App itself.
That being said, it is possible that your newer classes have a quite different code signature which may not "flow" with the existing classes.
Solution: Modify or remove the previous migrations since the new migration will create a new data structure that won't use or need them

How does ASP MVC 4 know which db migration you're on?

I have been developing my app in a code-first approach atop an exisiting database.
Only now do I have a need to run a migration. I don't want to destroy this database when my model changes because it is very large and it has nice sample data in it.
How can I run a migration without the framework telling me that there are pending changes to apply? (The code runs anyway as I do my migrations from Rails-tho I would like to do them from here)
I do not want to set up automatic migrations because I am working on a big database with lots of seeded data that I do not want to delete/recreate. I also want to have control over what is made, deleteded and when.
This is also needed for when I take it to production, I'd like to roll out the changes via Migration instead of manually. How can I migrate by adding in/removing the fields I want and not have EF care about what it is I do?
If I know how it knows which one it is on (like Rails) can I trick her into thinking that she can run the migrations I want?
I thought that setting the initializer by:
Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>
would take acre of it, but it does not.
To answer the question in the title, because there's a sys table __MigrationHistory which tells EF that there is a difference in your tables vs what the database has.
As far as how to do it (from package manager console):
Enable-Migrations
In the configuration class set AutomaticMigrations = false;
Set your Database.SetInitializer<Context>(null) so it doesn't DropCreate or Update
AddMigration <name> to queue any pending changes to a change model
Update-Database will call the MigrationName.Up method to alter the database with any changes (sans losing data).
There's a Table "__MigrationHistory" that EF uses to store Migration Name / Order. You can backup this table in your dev environment, then delete these records. When you deploy to production, you run the migrations. Another option is use Database compare (dev / prod) and get scripts to change your tables / data.

Entity Framework 4 code-based migrations don´t work after calling CreateDatabaseIfNotExist

I have a MVC 3 project were I use code based migrations together mith automatic migrations(this works).
When I install this project on a new server the database is created by CreateDatabaseIfNotExist initializer, cause I´m using the seed method of this. After executing this I have a __MigrationHistory table with one entry. The model hash of this entry is exactly the same like the last one from my developement server. On my development server I have an entry for each of my code based migration in the __MigrationHistory table.
Now the problem is that when I try to run the migrations on the new server, I expected them to say to me "nothing to do, cause model hash is same", but instead of this the migrations seems to look only for the MigrationId in the database and try to execute every migration whose MigrationId is missing. Of course this leads to Exceptions, cause the migration tries to add database structures already there.
I think this should be a very common scenario, so is there a kind of workaround for this? My workaround for the moment is to copy all contents from the __MigrationHistory of the development system to the new server, but this is very tricky, due to the dealing with the modelhash as varbinary. Is there a better solution or did I understand some logical things wrong?

Resources