moving to a new database with Code First Migrations - entity-framework

I have recently started using code first and migrations and I'm pretty happy with it.. I have been following the constant pattern of add-migration and update-database!
I have just tried to move from localdb to SQL Express and im having a real pain..
when I try and run the application.. I get the follow error..
Cannot find the object "dbo.AspNetUsers" because it does not exist or you do not have permissions.
In my Global file I have..
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
Any ideas? It looks like the core forms tables are not being created?
if I run my application without the Initializer in the global file I get this.
Migrations is enabled for context 'ApplicationDbContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.
Thanks
Ste.

Related

How to recover from Entity Framework nightmare - database already has tables with the same name

How do you get EF back in Sync with code without losing data when Update-database returns the following message
Error Message: System.Data.SqlClient.SqlException (0x80131904): There
is already an object named '' in the database.
I originally wrote this as a self-answering question as I had struggled with the proble for some time, as had a few colleagues, but unfortunately, my answer was deleted and I can't recover it.
Since it's a situation that I suspect can happen several times as people try to "clean up" old migrations, I thought I'd document it with step by step instructions.
Description of the situation we found ourselves in:
We couldn't can't create a new local database because the init script was incomplete, and couldn't apply updates to the production database because the migration scripts create tables that already exist. And, we didn't want to delete production data.
Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.
Error Message: System.Data.SqlClient.SqlException (0x80131904): There
is already an object named '' in the database.
Problem Background:
To understand this in more detail, I'd recommend watching both videos referenced here:
https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx
To summarise, EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.
Solution: What we need to do is to trick EF into thinking that the current database is up to date, while "not" applying these CreateTable commands since the production database already exists. Once production DB is set, we still need to be able to create local databases as well.
Step 1: Production DB clean
First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts.
Open your production database and delete/drop the dbo.__MigrationHistory table.
Step 2: Local environment clean
Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.
Step 3: Recreate Initial
In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts).
Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code.
If you had any seed operations in the previous Configuration.cs, then copy that across.
Step 4: Trick EF
At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.
Step 5: Update-Database
With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like.
Now, uncomment that code and save.
You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.
Step 6: Confirm EF is ACTUALLY up to date
If you had code that hadn't yet had migrations applied to it, this is what I did...
Run "Add-Migration MissingMigrations"
This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.
Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.
Step 7: Re-confirm and commit.
Build, test, run. Ensure that everything is running then commit the changes.
Step 8: Let the rest of your team know how to proceed.
When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.

Entity Framework code first - update database in production

I have enabled migrations. I am not using automatic migrations and I do not want to use them.
I have done 3 migrations.
In my development environment I am updating database via VS using the command
Update-Database -verbose -StartUpProjectName EntityFrameworkContext -TargetMigration <MigrationName>
In my devlopment environment, everything works correctly.
Now, I must update the database in production environment. I am using following command
Update-Database -verbose -StartUpProjectName EntityFrameworkContext -TargetMigration <MigrationName> -script
I run the generated script on production database. No error. The table __MigrationHistory looks to be good (I have just some doubt about the column Model that is different from dev environment). In this tabel I have the correct number of rows and the column MigrationId is correctly filled.
The database is exactly the same of the dev database. I have checked it.
I have updated also the program.
But, I do not understand why I still have always the same error:
The model backing the 'PublicAreaContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I am going crazy.
Thank you for your help

EF 7 Migration to Existing Database

I am working on a web project using ASP.Net 5 and EF7.
I have imported all the tables from existing database onto my models in my project. However, I am having problems in regards with migrations.
I have created the initial migration, made some changes on particular entity, create another migration following the changes I have made and now want to apply the changes on the database.
After running this command below:
dnx ef database update [Migration]
the dnx is trying to apply the 'initial' migration with all the entities which are already in database and this causes an error as below:
{ There is already an object named ['EntityName'] in the database. }
Can you please advise on how to do the migration on the existing database?
Thanks
Saeed
In EF6 you would run a migration with the -IgnoreChanges flag and it would take a snapshot of the model without any Up() code. This is missing from EF 7(EF Core) as indicated here.
The workaround for now is delete or comment out the code for existing database objects from the Up() code of the migration and then update-database. Subsequent migrations will then include only the changes.
After 2 days I found a way for EFCore that is not in google and internet!
How My steps works?
When you have a database with 10 table and you have data in tabales that you don't want to clear's data.and after this you will create new models in your code first and runnig to existing database and you will get error "Invalid object name 'tableName'." for query to new tables and you want to create migrations and do update it to existing database but first migration will create all queries for old and new tables if you run update-database you will get "There is already an object named ['EntityName'] in the database." for your initial migration.
How fix it?
Delete all migrations and snapshot in you database project
Delete __EFMigrationsHistory table in your existing database (if exist)
Run in Package manager console:
Note before run: This code will create new context and models of your existing database to Data folder so don't forgot to check you have not Data folder in your project.
Scaffold-DbContext "your connection string"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data
Run in Package manager console:
Note before run: Create first migration for initial database with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Add-Migration initial -Context OldDataBaseContext
Delete all code in Up method inside of created initial migaration in step 3
Run in Package manager console:
Note before run: Update databse with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Update-Database -Context OldDataBaseContext
Delete data folder that created in Step 2
Go to snapshot and initial migration classes and change the deleted context from Data folder to main context that is exist in your database project (just fix it for build)
Run:
Note before run: Add migration for main context that have new database changes
Add-Migration newUpdate
Run:
Update-Database
I Hope this help someone.
If you are strongly believe, that new (EF7) database schema will match your old database schema (including index and key names) - you may run 'Initial' migration to empty (temporary) database and then copy __EFMigrationHistory table from there to your real database.
Otherwise, I recommend you create empty database using migration and use sql insert into ... select commands to copy data from your old database. Without this, you will receive exceptions when upgrading database later - for example changing index will lead to DropIndex and CreateIndex migration commands, and DropIndex will fail because there is no index with this name (index exist with other, pre-EF7 name).
In my projects - old (from EF6) and new database schemes are different, and I used second option.

Script EF migration seed from Configuration class

I have EF migrations working nicely, but I also want to generate the sql script for the seed data from my DbMigrationsConfiguration class.
The seed data runs ok when I do Update-Database, but when I do UpdateDatabase -Script I do not get the sql for the seed inserts. I tried -Verbose on a normal Update-Database but I do not see the seed statements output there either.
Is this possible?
No it is not possible. Configuration class is not part of migration itself - it is infrastructure executing the migration. You have single configuration class for all your migrations and its Seed method is executed after every migration run - you can even use context for seeding data and because of that this method is executed after the migration is completed = it cannot be part of migration. Only content of the migration class is scripted.
Whether you are using EF or EF Core, a solution/workaround is to have SSMS generate the seed script for you:
Start with a clean database generated by your DB initializer and seed method. Make sure the data you want scripted is in there.
Using SSMS, right-click the database, go to Tasks > "Generate Scripts...", and follow the wizard. Under Advanced options, be sure to select "Data only" for "Types of data to script".
From the generated script, copy required seed statements over to your target script.
I know it's bit of an old thread but, here is an answer that could help someone else looking for an answer.
You can use the Migrate.exe supplied by Entity Framework. This will allow you to run the Seed method on the database context.
If you need to run a specific Seed method you can place that in a separate migration config file like this:
Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
Command:
Migrate.exe MyAssembly CustomConfig /startupConfigurationFile=”..\web.config”
Look for it in the NuGet packages directory: "..\packages\EntityFramework.6.1.3\tools"
You can specify migration configuration as an argument to it. The CustomConfig should contain your code based Seed method. So, This way you do not require SQL scripts to be generated from the migration.
More info here:
http://www.eidias.com/blog/2014/10/13/initialcreate-migration-and-why-is-it-important
http://www.gitshah.com/2014/06/how-to-run-entity-framework-migrations.html
Using this solution, you do not need to generate an SQL script and can run multiple Seeds for different environments.

MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"

I started off my project by using Entity Framework Code First. When I was ready I uploaded my database and code to my host provider. Everything worked.
I need to add a new field to one of my classes and I don't want to loose the data in the database. Thus, I tried following some blog posts about using Code First Migrations. I did the following:
I backed up my remote (production) database.
I attached this database locally
I added the property to my class
PM> Enable-Migrations
PM> Add-Migration AddSortOrderToCar
PM> Update-Database
At this point I created a .bak file of the local database and then used that file to 'restore' to the remote one.
Lastly, I published the code to the remote site.
When I visit the site I get the following error message:
The model backing the 'blahblah' context has changed since the database was created. Consider using Code First Migrations to update the database.
What am I doing wrong?
From my experience that suggests that migration table is out of sync (even if your data isn't), and that's been part of the db schema now (since 4.3 I think - under system tables).
There could be many reasons and ways to experience that error , but most of the time...
The problematic part is some combination of manually backing/restoring the full database with code changes alongside - I'm not entirely certain as to why always.
In short, even if Db-s are the same migration table data might not be - and hash comparison may fail (still full restore sounds like good enough - but you have 'two sides').
What works for me is to use
Update-Database -Script
That creates a script with a 'migration difference',
which you can manually apply as an SQL script on the target server database (and you should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...
Remove the migration table (target - under system tables) - as per http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx comments in there - that should fail back to previous behavior and if you're certain that your Db-s are the same - it's just going to 'trust you',
As a last resort I used - make a Update-Database -Script of the full schema (e.g. by initializing an empty db which should force a 'full script'),
find the INSERT INTO [__MigrationHistory] records,
just run those, insert them into the database,
and make sure that your databases - and code match,
that should make things run in sync again.
(disclaimer: this is not a bullet proof to work at all times, you may need to try a few things given your local scenarios - but should get you in sync)
I think in step 6 you need to run Update-Database -Verbose
Also this link is very helpful for updating database in EF with Scaffolding
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-entity-framework-scaffolding-and-migrations