MVC 5, Database migration - entity-framework-6

I'm new to MVC5
I've this error when i have executed the command
-update-database:
I've three tables, when i did execute the command two among them were populated, and the third one were not.
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied
to the target database. No pending explicit migrations. Running Seed
method.
at
System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
command)
Sequence contains no matching element

Related

I dropped a table and want to create a new one - but I don't want to lose my other tables

This is probably really simple/obvious but I am new to this -
I have a database with some tables, let's say tA, tB and tC. In a migration I dropped tC, because at that point I needed to working on a different branch. However, I'm now working on a branch in a project that needs tC to exist.
The migrations for creating all tables are present on this branch.
I don't care if tC is empty. But if I run rake db:create, will it then re-create all tables? Because I do not want to lose the data in the other tables, tA & tB.
TL;DR - How to create a table (which I dropped in an earlier creation) without also recreating (and losing the data of) the tables I did not drop?
How did you drop the table tC? Is it through console/command line? If yes, then to recreate the tC table, you have 2 choices:
Create a new migration file to only create table tC (optimal and easiest fix)
bundle exec rails g migration CreateTableTC
Then add the new migration with this conditional statement:
unless table_exists?(:table_tC)
create_table :table_tC do |t|
........
end
end
Then run this command on your terminal:
bundle exec rake db:migrate
This will create table tC if your database hasn't got one, will not erase data on other tables, and will not be executed if your database has table tC
Use GUI for your database (if you are using postgres, you may use PgAdmin)
Here's what I ended up doing: using the Rails console, I simply ran the migration that created that particular table in the first place again. See this Q&A: Run a single migration file.

MVC 4 Server error

I am new to mvc in asp.net, so I have started with movie application in mvc with code first approach. My problem is when I change or add new field in movie class, then I got an error like
The model backing the 'MovieDBContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
So anyone knows the solution for it with code first approach after changing or add any new field ...
using three command its solve which are list below.....which we have to write in package manager console
1)Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDBContext
2)add-migration Initial
3)update-database
but why this error occurs and is there any other solution for it without the above three commands in mvc 4?
You have changed the Code First models since applying them to your database, so you need to reupdate, to apply these changes. First you add a new migration. Do this by typying this into the package manager console:
add-migration migrationName
migrationName should be unique and descriptive of the changes. After running this command, you should have a migration file, which you can apply by running:
update-database
Given that the changes are valid, they should now be applied to your database.
You have to do this every time you make changes to your CF models.

Multiple DB Contexts in the Same DB and Application in EF 6 and Code First Migrations

I'm new to Entity Framework. I am trying to setup an MVC Application what uses EF 6. I am using Code First Migrations. I am using Areas in the app and would like to have different DbContexts in each area to break it up. I know EF 6 has ContextKey, but I can't find complete information on how to use it. Currently I can only use migrations one context at a time.
Can someone give an example with enough detail for a new person to EF like me to understand and use.
Entity Framework 6 added support for multiple DbContexts by adding the -ContextTypeName and -MigrationsDirectory flags. I just ran the commands in my Package Manager Console and pasted the output below...
If you have 2 DbContexts in your project and you run enable-migrations, you'll get an error (as you probably already know):
PM> enable-migrations
More than one context type was found in the assembly 'WebApplication3'.
To enable migrations for 'WebApplication3.Models.ApplicationDbContext', use Enable-Migrations -ContextTypeName WebApplication3.Models.ApplicationDbContext.
To enable migrations for 'WebApplication3.Models.AnotherDbContext', use Enable-Migrations -ContextTypeName WebApplication3.Models.AnotherDbContext.
So you have to run enable-migrations on each DbContext separately. And you have to specify a folder for each Configuration.cs file to be generated...
PM> Enable-Migrations -ContextTypeName ApplicationDbContext -MigrationsDirectory Migrations\ApplicationDbContext
Checking if the context targets an existing database...
Code First Migrations enabled for project WebApplication3.
PM> Enable-Migrations -ContextTypeName AnotherDbContext -MigrationsDirectory Migrations\AnotherDbContext
Checking if the context targets an existing database...
Code First Migrations enabled for project WebApplication3.
To add migrations for each DbContext, you do it like this by specifying the fully qualified name of the Configuration class:
PM> Add-Migration -ConfigurationTypeName WebApplication3.Migrations.ApplicationDbContext.Configuration "InitialDatabaseCreation"
Scaffolding migration 'InitialDatabaseCreation'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration InitialDatabaseCreation' again.
PM> Add-Migration -ConfigurationTypeName WebApplication3.Migrations.AnotherDbContext.Configuration "InitialDatabaseCreation"
Scaffolding migration 'InitialDatabaseCreation'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration InitialDatabaseCreation' again.
And you run update-database the same way:
PM> Update-Database -ConfigurationTypeName WebApplication3.Migrations.ApplicationDbContext.Configuration
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201402032113124_InitialDatabaseCreation].
Applying explicit migration: 201402032113124_InitialDatabaseCreation.
Running Seed method.
PM> Update-Database -ConfigurationTypeName WebApplication3.Migrations.AnotherDbContext.Configuration
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201402032113383_InitialDatabaseCreation].
Applying explicit migration: 201402032113383_InitialDatabaseCreation.
Running Seed method.

Entity framework manually deleted tables cant be generated from EF migration

I have created migration and created the database and the tables . For example the tables are
A B C D E . Now again I have changed some part of code and ran update-database command . Everything went smooth and nice and the tables showed the columns . Now accidentally I manually deleted one two tables D and E. Now when I try to run the migration with update-database . It runs properly but doesn't create the tables which I deleted manually . I tried to delete the existing migration and re-run update-database . It gives the error that apart from the two tables . There already an object existing in 'A ,B, C ' bla bla name.
Any idea how to get rid of this situation without dropping database and recreate the deleted tables using migration ? Cause i dont want to drop the database as it contains the data in rest of the tables. How to proceed in this situation where I have existing tables in database and accidentally I have manually deleted few tables from SQL server from SSMS .
How to recreate the tables again using migration ?
Oh my entity framework version is 6.0.2
EF Migration history is stored in the table _MigrationHistory. Remove the table from the Database. Caution: This will erase all the Migration history and you will have to re-create all the tables
I finally figured out the solution . Its basically change in strategy how we use migration . The Migration Add-migration only checks the Models and the previous migration timestamp cs files possibly . so until and unless we provide update-database command in nuget . it Never actually gets to know which Tables have got deleted manually . So to the context when we try to perform some migration like alter on the tables . It causes problematic migration since that table doesn't exist on the database but the migration assumes it is already there . So for that there is a manual work . Here are the steps after we have deleted a table manually from the database
Check the models existing in entities with correspondence to the database table . If we have found there are some anomaly in the database table which is missing from database but it exists as entity that means. They both are not in sync with each other. So we have to find the model => Table relation for each .
If we have created initial migration with all tables then copy the deleted createTable code from the migration file .
Paste it into the last recently generated migration file. And then generate the script or run the update-database command . That would create the deleted database table . However there is no automatic command which would both sync between all entities and the database tables . That's something which we have to track partially manual in migration.
you can do a simple trick here, remove the specific migration history rows, which affect your deleted tables from
dbo.__EFMigrationsHistory
then run update-database command,
enjoy
IMHO the most straightforward solution is to generate SQL script form the migration and run only a part of the script, that creates missing tables.
Update-Database -Source MigrationBeforeCreatingTables -Target MigrationAfterCreatingTables -Script
not best but possible way:
1)create a new migration, don't update the base
2)find migration that added tables you need
3)copy up and down parts from that old migration
4)past those things in the new migration file
5)update the database by the new migration

db:migrate creates sequences but doesn't alter table?

I have a migration that creates a postres sequence for auto incrementing a primary identifier, and then executes a statement for altering the column and specifying the default value:
execute 'CREATE SEQUENCE "ServiceAvailability_ID_seq";'
execute <<-SQL
ALTER TABLE "ServiceAvailability"
ALTER COLUMN "ID" set DEFAULT NEXTVAL('ServiceAvailability_ID_seq');
SQL
If I run db:migrate everything seems to work, in that no errors are returned, however, if I run the rails application I get:
Mnull value in column "ID" violates not-null constraint
I have discovered by executing the sql statement in the migration manually, that this error is because the alter statement isn't working, or isn't being executed.
If I manually execute the following statement:
CREATE SEQUENCE "ServiceAvailability_ID_seq;
I get:
error : ERROR: relation "serviceavailability_id_seq" already exists
Which means the migration successfully created the sequence! However, if I manually run:
ALTER TABLE "ServiceProvider"
ALTER COLUMN "ID" set DEFAULT NEXTVAL('ServiceProvider_ID_seq');
SQL
It runs successfully and creates the default NEXTVAL.
So the question is, why is the migration file creating the sequence with the first execute statement, but not altering the table in the second execute? (Remembering, no errors are output on running db:migrate)
Thank you and apologies for tl:dr
I separated the creation of sequences and the altering of tables into two migrations.
When running:
rake db:migrate
The sequences would not be created nor the tables altered and the rake would run successfully.
If however, I ran the migrations seperately:
rake db:migrate VERSION=1
rake db:migrate VERSION=2
The sequences would be created, and the tables altered as expected.

Resources