Entity Framework 6 just deleted my database? - c#

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

Related

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 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

migration synch developmental and production databases

I am using MVC 5 with NET Framework 4.5.1. with Code-first. I am also using Migrations with the SQL 2012 server and (localdb)\v11.0.
I am in the middle of developing a project using C# and MVC5. During development, I created a lot of new tables in my developmental computer and changed a the "Name" field which I believe the system makes an index for. I added it and deleted it several times.
After that, I added a lot iof new unrelated tables, but for some reason, my migrations started giving me foreign constraint errors due to the indexes for the "Name" field. These errors kept multiplying as I fixed them, so, I decided to revert back to an initial state in the migration, and reset using the current position as a new starting point. I was hoping, that the production table would look at this new starting point in the development db, and resynch itself to the developmental state. I thought that I had read somewhere that the production db matches itself to the developmental db and updates itself. I believe that there is a migration file in the production db which would match itself to the file in the developmental db -that file was clearly out of synch. I have considered deleting the data in it, but I am holding off till I get advice.
Anyway, I changed the name of the migrations directory in the Dev computer and excluded it from the project. Then I reinitialized my tables (using a new db name in my local db) on the dev computer and re-loaded it with the initialization data. It all worked.
Now, I had a new problem, my production db and my developmental db were different, and my migration in the dev computer was setup to create new files whereas the one in the production state was expecting the older migration. Every time I tried to update the production db using the development computer, I kept getting an error that the files existed - which of course they did.
So, I commented out all the create files in my migration file and re-tried. Now, the production db would start, but would not run because the updated code had new fields it was referring to which did not get created in the production db. So, on my production db I started to get errors of all the fields that were missing. I tried to make automatic migrations true as well, that did not work. I am guessing, the only way to fix this is to go in manually and synch the fields one by one.
QUESTION 1: Is there an automatic way to synch (using migrations) the production db and the developmental db so that they become the same same as the developmental db?
QUESTION 2: Keeping in view the above scenario, what would have been a better way to go about to re-set the miggrations with a production db out as well?
I found a solution. The folks at Red-Gate have a great SQL tool called the SQL Compare. It compares the database file structures and even makes them EXACTLY the same, at a click of a button.
But, before you use it, be sure you ONLY compare "tables", as opposed to everything which includes "users" and "roles" and a lot more. That is because when you run the software, it backups, deletes and re-creates, and if the roles or users get deleted, the software can no longer access the database and everything gets deleted! Also... MAKE A BACKUP! (I lost all my test data on my first try)
http://www.red-gate.com/products/sql-development/sql-compare/
(This is not a sales plug for the folks at Red-Gate. I dont know them, but their tool helped me immensely - its a good tool, easy to use, and FREE for 14 days! - and I list it here so that anyone else, and I am sure there are many, who may be stuck like me can be helped.)
April 24 2015
Ok. There is more to it after you synch both the databases so that they look exactly alike.
Create a Back up of your production data *
Delete the Migration folder in your developmental folder.
Enable Migrations again
Add an initial migration
Update the local database
Now you have your local completely set up *
Go to the host database
Find the table called "__MigrationHistory" in Host/Production
Delete all the data (you want to purge it) ("__MigrationHistory" (Host))
Now copy all the data from the local "__MigrationHistory" to the hosted "__MigrationHistory"
(There will be your one single line i.e. the initial one you created above")
Now the data has been saved and every thing will be synched and it will work.
You can begin development again.

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

how to detect the new database when change database in asp.net mvc4

The problem that when i change the new database then application not detected the new database and retreive error
The model backing the 'DBContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
but i don't using Migrations so i don't update-database by Package Manager Console
How can i fix this problem?
Actually it does detect changes in your database. The database differs from the model. The error message.
This error is thrown when the hash stored in the migrations history table does not match a calculated hash. (Have a look at __MigrationHistory table, might be under system tables)
If you delete this table the check is essentially disabled. You can achieve something similar by adding Database.SetInitializer<YourContextType>(null) to the startup of your application. The latter disables database creation from within that application, so if you want to create the database by code, you would need to do this from a separate application (for example an console app). I prefer to go this way for web applications.
Secondly: if you change your database manually (change columns, add tables, etc.) you need to adjust your model. So for each DDL statement, change your code.
If you are not using code first, you could update your existing model in the designer.
I ran into this problem when I first started with code first and mvc. the answer below is absolutely correct but you should go to the ASP.net website and do some tutorials on code first migrations. you need a better understanding how update database and initialize and migrations work.

Categories