获取初始实体框架迁移脚本 [英] Getting Initial Entity Framework Migrations Script

查看:238
本文介绍了获取初始实体框架迁移脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚安装了Entity Framework Migrations,将一个属性添加到了一个类,并给了EF Migrations一个旋转。

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.

现在,我想为生产数据库的这个初始化使用Migrations创建一个更改脚本。注意,有一个预先存在的数据库,因为我将它应用于现有的项目。

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.

我的迁移是:

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

但是,这给了我错误:


'201204102238194_Au​​tomaticMigration'不是一个有效的迁移。

脚本化它们之间的升级时,显式迁移必须用于源和目标。

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

只是为了看看会发生什么,我颠倒了这两个参数(向后迁移),并且获得了添加 -force 标志(新的列删除)之后的脚本。

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).

如何获得第一次迁移的脚本?

推荐答案

开始使用现有数据库的EF迁移的正确方法是从添加包含当前数据库元数据的空迁移开始。

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

这应该给你一个初始迁移,没有什么,但包含当前模型的元数据。如果您扩展了代码模型以覆盖数据库中已经存在的更多表格,那么您以后可以添加 -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.

这篇关于获取初始实体框架迁移脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆