Getting code-first entity framework Azure back in sync - c#

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

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 code-first and existing database

I'm working on an application with asp.net mvc that supports install, remove plugins.
When I want to install a new plugin I have an Install method that registers new routes and ...
For database, I use a code-first approach for creating database and every plugin has it's own context class.
My question is: when I want to install a new plugin, I need to create additional tables in my existing database, or create a new database if the database does not yet exist. And if those tables are already there, nothing should be created.
How do I achieve this?
Thanks in advance
Code First Migrations has two primary commands that you are going to become familiar with
Add-Migration will scaffold the next migration based on changes you
have made to your model since the last migration was created
Update-Database will apply any pending migrations to the database
When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database each time you change the data model. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data.
This method of keeping the database in sync with the data model works well until you deploy the application to production. When the application is running in production it is usually storing data that you want to keep, and you don't want to lose everything each time you make a change such as adding a new column. The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database.
I recommend to have look following link which makes you more clear about your problem.
https://msdn.microsoft.com/en-us/data/jj591621

Migrating changes to DB

I'm developing a web app in ASP.NET with Entity Framework and a SQL Server database.
I'm using Code-First approach. Until now everytime I made a change to the database schema (added tables, changed tables rows (add or remove)) the database was recreated. Since it was not a live version yet.
Now, I will deploy the application, while I continue to develop it.
How should I proceed to update a live version of the database with the changes I make locally? That, without losing data.
So, per example, I create a new table and a add or remove a few rows in another tables with a code first approach. Everything is tested and working and now I want to update the live version. How would I proceed?
You need to use the Code First Migrations, check out this Link to MSDN
Code first migrations will take the current state and make it 'Initial Migration', all changes from then on are scripted as incremental updates. Your change flow should look like this:
Make change (add table through classes, etc etc)
Generate a Migration
Run the Migration
Test the Change
Deploy the change to the live system
When you deploy the change, in your publish settings you can inform it to run the migrations on application start up, or on request.

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());

Controling EF database creation and migration

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.

Categories