Getting Initial Entity Framework Migrations Script

2020-05-23 16:12发布

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?

1条回答
Anthone
2楼-- · 2020-05-23 16:34

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.

查看更多
登录 后发表回答