Running "dnx ef migrations add" twice or more doesn't create blank Migrations - entity-framework-migrations

I am using Entity Framework 7 RC1
I run the following
dnx ef migrations add InitialMigration
dnx ef migration add MyCustomMigration
I was expecting MyCustomMigration to have empty Up and Down method but instead it has
Up:
migrationBuilder.DropForeignKey(name: "FK_XXX_XXX", table: "tbl_XXX");
migrationBuilder.AddForeignKey(
name: "FK_XXX_XXX" ....
onDelete: ReferentialAction.Cascade);
Down:
migrationBuilder.DropForeignKey(name: "FK_XXX_XXX", table: "tbl_XXX");
migrationBuilder.AddForeignKey(
name: "FK_XXX_XXX" ....
onDelete: ReferentialAction.Restrict);
If I run the command more than two times it does exactly the same
dnx ef migration add MyCustomMigration2
creates the same Migration File with the exact same contents
I want to create an empty migration file so I can put in my custom migrations. However it seems there is a bug there.

This looks like issue #3751 which should be fixed in the nightly builds.

Related

Can I delete an empty EF Migration safely

I've just reviewed a colleague's work and there is an empty EF migration in his PR (up and down methods contain no code). There is another migration after this with DB modifications.
I believe that this empty migration can be deleted on the basis that it does absolutely nothing. There should be a corresponding entry in the _MigrationHistory table, which can also be deleted safely, in my opinion.
My colleagues believe that it should be left in there "just in case".
Are there any EF experts who can say which approach is best, and why?
Тhe truth is somewhere in the middle. You can delete it, but do not delete the migration file directly.
-> Removing A Migration
The following command removes a migration:
[Command Line]
dotnet ef migrations remove
[Package Manager Console]
remove-migration
You will use this command to remove the latest migration. This will remove the class file that was generated for the latest migration and it will also revert the ModelSnapshot file back to the state of the previous migration. If there are no pending migrations, an exception will be raised. If you want to remove a migration that has been committed, you must reverse the migration first (see below).
You should always use commands to remove a migration instead of simply deleting the migration code file, otherwise the snapshot and migrations will fall out of sync with eachother. Then future migrations will be based on a model that is incorrect. Nevertheless, the remove command will recognise if migration files have been deleted and will revert the snapshot accordingly.
If you need to remove a migration that was generated before the most recent one, you must remove all sunsequent migrations first, then adjust the model and then create a new migration to cater for the changes.
Sores: https://www.learnentityframeworkcore.com/migrations

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.

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

Compact all migrations

I have multiple migrations:
.....
create table
add column
add another column
remove other column
6 .....
Is there any ablity to change all these migrations to one new migration which will create the same database schema?
I think that you can change remove those migrations and create a new one, called for example "initial_schema", where you should put the content of the schema.rb composed by all your previous migrations.
Consider that rails generate a schema.rb for you when you run those migrations.
Then you need to drop all tables in your database and run again rake db:migrate.

Resources