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!
Related
EF 6.2
SQL Server 2012
I am getting the exception:
Unable to update database to match the current model because there are
pending changes and automatic migration is disabled...
I have done my research here, here, here
I have had a solution working for a long time now with no issues. And in fact I made a change to the database a couple of days ago and all was well using the standard add-migration followed by update-database with no issues.
However today I made a change to the database again and did add-migration followed by update-database. But when I run the application I get the above error.
I make sure the migrations run by including the following in my Application_Start:
ConfigurationPlatform configurationPlatform = new ConfigurationPlatform();
DbMigrator migratorPlatform = new DbMigrator(configurationPlatform);
migratorPlatform.Update();
and the configuration class looks as follows:
public sealed class ConfigurationPlatform : DbMigrationsConfiguration<TreasurePlatformDbContext>
{
public ConfigurationPlatform()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
ContextKey = "TreasurePlatform";
}
protected override void Seed(TreasurePlatformDbContext aContext)
{
// This method will be called every time after migrating to the latest version.
// You can add any seed data here...
}
}
I have also tried:
Running add-migration again but it produces NO changes
Turning on automatic migrations and it STILL complains
I am confident the POCO table models match what is in the database. Has anyone got any suggestions or thinks I can try?
Entity Framework stores a snapshot of the model in each migration. It sounds like your snapshot has become out of sync with your current model. There are two potential ways to fix this.
Method 1
This will create a blank dummy migration which contains a snapshot of your latest model but not actual code. Unfortunately it does mean you will have additional code in your project.
Run Add-Migration <pick_a_name> –IgnoreChanges
Method 2
This will rollback your database and then recreate the migration with an updated snapshot.
You can only do this if you haven't pushed the migration to Git or updated any other databases. Otherwise any other updated databases will also need to be rolled back to the second from last migration on step 1 of this process.
Update-Database –TargetMigration <second_last_migration>
Add-Migration <full_name_including_timestamp_of_last_migration>
You need to include the timestamp so that migrations knows you want
to edit the existing migration rather than scaffolding a new one.
This will update the metadata for the last migration to match the
current model.
Update-Database
Source https://learn.microsoft.com/en-gb/ef/ef6/modeling/code-first/migrations/teams#resolving-the-merge-conflict
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.
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.
I have an application using a EF model for the database. This application is going to run on multiple computers in the same network using one database. To make sure this works ok when there are updates. I want to control the migration and installation of the database.
I thought I could disable the EF initializer and in my application startup checks using context.database.Exists() and context.database.CompatibleWithModel if the application matches the database. If this is not the case I want to create it after I check if all client are offline.
But my problem is when I run context.database.create() ,
I get an error
{"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."}
What is the best approach to controlling the creation of the DB and migrates from code? And not from the initializer.
The problem you've got seems not related to db creation. Your model just simply does not comply any more with what migrations states. Just run add-migration script to regenerate migration files and everything should work fine. If you would like to allow automatic migrations (not required to regenerate migration classes after model changes - but generaly this is a bad idea) just set AutomaticMigrationsEnabled = true in Configuration class for migrations and this will as well fix your error. To control migrations from code the best thing you could use is DbMigrator. You use it like that:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
With the Update method you can define to which migration you want to migrate your db.
I've been playing with Azure and MVC5/EF6 with Code First migrations and managed to find something that I wouldn't know how to fix if it was production.
Here's what I did:
Create a model named MyModel with one property: PropA
Enabled migrations and created a migration named Initial
Published to Azure - great - works fine!
Deleted my Initial migration and added a second property to MyModel named PropB
Created a new migration called Initial2
Published to Azure - now azure is crashing because it can't find the field PropB
I've tried setting AutomaticMigrationsEnabled = true; but it didn't make any difference.
So my question is: If this were a production database and this happened - how would you get the Azure database back in sync and migrate the changed models?
Manually add code to the migration in the "up" and "down" methods to sync your code as required
Before you use SQL compare, be sure that you're running at least a "standard" database tier in Azure. If not, you'll get errors just trying to do the compare. Note that you can change your tier, do some commands, and change the tier back within a few minutes.
Also, in your list of steps, after step 5, do an update-database. That will get your local database in sync. Next, when you publish to Azure, make sure to select that database (dropdown next to the connection string), and then be sure that execute code-first migrations is checked.
Cheers