Azure Entity Framework Code First Migration after reactivation of subscription - c#

Good day...
I have a Web application and SQL Server database in Azure, that has been working great, designed from the very start to use Code First EF 6.1.3 and Azure.
Microsoft recently deactivated my Azure account, but I got them to re-activate it.
After it was re-activated, though, on first load of the application, it attempted to run Code First Migrations again. All of the tables are still out there in the database, including the MigrationHistory table, so I cannot figure out why it is attempting to run all migrations again.
The table that it breaks on is AspNetRoles, which is in the very first migration file listed in the MigrationHistory table.
Any ideas what I need to do to get it to see that they are already applied?
Thank you!

The issue has been resolved, but we could not determine the reason for the disconnect. I got in contact with Microsoft Support and they helped me to get up and running again. In order to restore the functionality of the system, and keep the existing data,
We:
Disabled migrations
Removed all evidence of migrations
Re-enabled migrations
Created an initial migration with the -IgnoreChanges flag
Performed an update-database
This got the migrations back in sync.
As explained to me, this was basically using a database-first EF method and from now on I will continue to use Code-first methods.

Related

Azure Mobile Service and EF Code First - context has changed error

I have an Azure mobile service backed by a SQL database. I’ve been happily deploying to this for weeks and manage my DB using EF Code First. Now though, I’ve hit a brick wall whereby any request to the mobile service breaks with an error:
The model backing the '[yourcontext]' context has changed since the
database was created.
The thing is though, it hasn’t!
I’ve tried the following:
1. Re-depoyed the service *several* times
2. Run ‘Add-Migration’ to see if it mystically picks up any new fields/properties
3. Run ‘Update-database’ which runs without any issues
4. Combinations of 2&3 over and over
5. Deleted the Migration History table
6. Deleted ALL tables from my DB and re-run update-database, which again completes without error
7. 6 then 3, which recreates the database
Any ideas how I can resolve this insantiy?
AFAIK, the Code First Migrations can be executed manually or automatically. I would prefer to choose the automatic migration. You could add the following code to App_Start\Startup.MobileApp.cs file for enabling automatic migration as follows:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Models.MobileServiceContext, Migrations.Configuration>());
Or
var migrator = new DbMigrator(new Migrations.Configuration());
migrator.Update();
Note: You need to either configure AutomaticMigrationsEnabled to true under Migrations\Configuration.cs without manually adding pending model changes to a code-based migration via Add-Migration or you could just use Add-Migration for adding pending model changes without set AutomaticMigrationsEnabled to true.
Based on your issue, I would recommend you changing the database name and use a new database to narrow this issue, also you need to remove the old migration files under the Migrations folder. Additionally, you could refer to adrian hall's book about Implementing Code First Migrations.
So I fixed it rather frustratingly by:
Exporting all my data out to a query window and saving the results to my local PC.
Renaming the old DB
Setting AutomaticMigrationsEnabled = true; and re-deploying
Letting the migration create the database (but this didnt create the table)
Setting AutomaticMigrationDataLossAllowed = true; #PanicModeOn
Re-deploying
Re-importing all my data
What a farce. Obviously I can accommodate this now but when my app goes into production this would be a MAJOR issue!

Entity Framework 6 just deleted my database?

I'm using MVC 5 with Entity Framework 6, automatic migrations are disabled, no seed is used and I'm scripting out my updates to production.
I'll hold up my hands and say I'm fairly new to MVC and EF.
I just uploaded a new codebase to production, and forgot that the model had changed. When I went to login to the new version, it threw and error page. Fine, I forgot to script the latest migration - I did that, hooked up to SSMS and found that the database was gone.
Slight panic, restore from backup (I'm not that daft!) and apply the migration and everything starts working as it should.
Why did my code delete the entire database when the model had changed? As said, automatic migrations are disabled and this behaviour doesn't happen on development machines, they throw an error about the model having been changed.
Edit to add: Whilst looking at the Initialisation patterns in Fernanda's answer, none of them say "Drop the database and then do nothing else". My database was dropped, the MDF and LDF gone, nothing is SSMS and nothing recreated in its place. If a blank database was created in its place I'd understand a bit more. That said, the user account had DBO on the database but not master, so would have been able to drop the database but not create a new one?
Read this about Database Initialization Strategies in Code-First:
http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
Check your dbcontext initialization and be sure that the option DropCreateDatabaseIfModelChanges is comment
//Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

Migrating Entity Framework without Migration Files

I am working on a project which is using Entity Framework code first for its data structure. It was created with code first, but was never migrated again and only has its initial migration data stored. Since then, the database has been modified directly through server explorer in VS2015.
There is no migration information about any changes and the database has critical information which I cannot lose.
Which brings me to my Questions.
If I create a new migration and update the database from it, will it wipe all changes which were not recorded in migrations and still leave the changes which were made as well?
The details of your question is a bit sketchy, but I will make some assumptions in order to help you along. Please correct where I am wrong.
I assume that you want to keep the data which resulted from the changes which were effected directly to the database, but you do not want to keep the changes that was effected to the database - in other words: keep the data but not the datastructures.
My advice is as follows
Always perform a full backup of your database when you are about to do something you are uncertain about.
If you can identify the tables you want to update, you can always use the SELECT INTO statement to create a quick backup of the specific tables only. These tables will not be removed when you do a EF database migration unless you explicitly script the deletion.
You can build the SELECT INTO statement into your EF migration via the Sql() method, or you can manually run the command against the database.
More information:
Click here to learn about EF code first migrations in general
Click here for a comprehensive code first migration reference
I believe following two posts will help you.
EF 4.3 Migration Walkthrough : http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
update:
Code First Migrations with an existing database
https://msdn.microsoft.com/en-us/data/dn579398.aspx

Entity Framework 6 and migration when I don't have a default Database

I have a solution where I do not have one default database. I have a master Database that are returning a connection string for the customer that is requesting data, and each customer has their own database. I am using migration (and has AutomaticMigrationsEnabled set to false) and code first.
The command “update-database” is “excecuted” from the code (Database.SetInitializer(new MigrateDatabaseToLatestVersion());).
The first time is it all working fine, but when I afterwards will add a migration, I cannot, because there are pending migrations. I can not run update-database from VS because the connections string is set on runtime.
What is the right way to handle a setup like mine, with migrations and Entity Framework 6?
Thanks very much in advance 
What you have is so called multitenant application. And yes, EF migrations can support such scenario, too.
You just have to change your migrator from the MigrateDatabaseToLatestVersion to a custom one that migrates the exact database the context is created for.
Then, forget about executing update-database from a powershell console. This always updates the default database! Instead, your custom migrator will automatically update the database you connect to.
Complete source code of the custom migrator can be found in my blog entry:
http://www.wiktorzychla.com/2013/05/entity-framework-5-code-first-multi.html
Be aware that due to a bug in eariler versions of EF, migrations in a multitenant scenario work correctly starting from EF 6.1.3.
Because of this bug, your multitenant application could incorrectly assign connection strings to newly created db contexts.
https://entityframework.codeplex.com/SourceControl/changeset/4187b1c308316a22b38ef533b1409024bc0f7406
Add-Migration and Update-Database from the console still refer to a database.
To create a DbContext, these commands either use its parameterless constructor (if you have one), or it instantiates an IDbContextFactory<T> if one exists and calls its Create method to get one.
The fact you don't use this specific database at run-time isn't really important, but you do need one somewhere at design time to allow you to add migrations.

Cannot run master locally because my EF Code First Migrations out of sync

I am running into a problem with EF6 code first migrations.
When I am in a lower sub branch where I am making my dev changes for new things to go out, I have migrations in that branch and my database has those changes.
When I switch to my master branch (i do not want to merge) and i try to run it locally, my migrations exist in my database but not in that branch of code.
I am trying to make a bug fix to go out to production from the master branch and do not want to run any new migrations but it tells me:
The model backing the 'DummyDBContext' context has changed since the
database was created.
How can i get around this?
You've really got two problems here.
The migrations history that is stored in your database (in the _MigrationHistory table) is out of sync with the migrations that you've got on the master branch. This is what's causing the InvalidOperationException to be thrown.
The actual database schema is now out of sync with the way EF is understanding your schema based on the migrations that exist in the master branch. Based on your current code (in master), the schema should really look like it did before you switched to the subBranch and made changes.
The simplest way out of this is to just roll back the 'subBranch' migration before switching back to master (By calling Update-Database -TargetMigration [NameOfPreviousMigration]). The downside is that you're going to have to re-run the migration any time you switch back to the subBranch.
Otherwise, the way around this is going to entail:
Manually deleting the migration history from the _MigrationHistory table.
Rolling back any changes that were made to the database schema by either setting the DbInitializer to DropCreate (which will delete all the data in your DB, so watch out w/ this one) or manually undoing any changes made to the schema by the migration.
And if you do go this route, you're going to need to re-run the migration from scratch when you switch back to subBranch either way.
Good Luck ;)

Categories