Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Initial Entity Framework Migrations Script

I just installed Entity Framework Migrations, added a property to a class, and gave EF Migrations a whirl.

My development database was promptly updated. So far, so good.

Now, I want to create a change script for this initial use of Migrations for the production database. Note there was a pre-existing database because I applied this to an existing project.

The migrations I have are:

PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201204102238194_AutomaticMigration
201203310233324_InitialCreate
PM> 

I thought I could get a delta script using the following:

Update-Database -SourceMigration:201203310233324_InitialCreate -TargetMigration:201204102238194_AutomaticMigration  -script

However, that gives me the error:

'201204102238194_AutomaticMigration' is not a valid migration. Explicit migrations must be used for both source and target when scripting the upgrade between them.

Just to see what would happen, I reversed the two parameters (backward migration) and did get the script I would expect after adding the -force flag (new columns dropped).

How can I get a script for this first migration?

like image 983
Eric J. Avatar asked Apr 10 '12 23:04

Eric J.


People also ask

How do you do initial migration?

Run the Add-Migration InitialCreate –IgnoreChanges command in Package Manager Console. This creates an empty migration with the current model as a snapshot. Run the Update-Database command in Package Manager Console. This will apply the InitialCreate migration to the database.

Which command generate SQL script from migrations?

With From and To The following generates a SQL script from the specified from migration to the specified to migration. You can use a from that is newer than the to in order to generate a rollback script.


1 Answers

The right way to start using EF migrations with an existing database is to start with adding an empty migration that contains the metadata of the current database.

I think that you have to roll back to a model that is compatible with the initial database schema. Then run the following command:

add-migration InitialSchema -IgnoreChanges

That should give you an initial migration, that does nothing, but contains the metadata of the current model. You can of course add migrations later with -IgnoreChanges if you've expanded your code model to cover more of the tables already present in the database.

Once you have that initial migration step in place, the scripting would work.

Generally I would not recommend to use automatic migrations unless you only ever intend to only use automatic migrations. If you want some kind of control over the changes to the database (including scripting them) then code-based migrations is the way.

like image 197
Anders Abel Avatar answered Sep 19 '22 05:09

Anders Abel