如何在 EntityFramework 4.3 中为现有数据库创建迁移?

发布于 2025-01-05 01:42:48 字数 88 浏览 1 评论 0 原文

所以我想开始 EntityFramework 4.3 迁移。我想知道是否可以将现有数据库转换为支持迁移的数据库,并让 EF 假设只有从那时起的更改才应被视为迁移。

so I want to get started with EntityFramework 4.3 migrations. I wanted to know if I can convert an existing database to a migration-enabled database and have EF assume that only changes from then on should be considered migrations.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静谧幽蓝 2025-01-12 01:42:48

这里发布了一个很好的演练:http://thedatafarm.com/data-access/using-ef-4-3-code-first-migrations-with-an-existing-database/

我想要的一个更改建议只是简单的评论删除 Up 和 Down 方法中的代码,直到部署迁移。之后,您可以取消注释代码,这样您就可以在以后需要时创建新的数据库。

A nice walk-through for this is posted here: http://thedatafarm.com/data-access/using-ef-4-3-code-first-migrations-with-an-existing-database/

The one change I would suggest is to simply comment out the code in the Up and Down methods until you have deployed the migration. After that, you can uncomment the code and that will allow you to create a new database if you need to later.

恍梦境° 2025-01-12 01:42:48

所以看来我正在寻找的是基于代码的迁移,当我设置 AutomaticMigrationsEnabled=false 时会激活该迁移。我的模型是从现有数据库生成的。要激活迁移,我需要做的就是启用迁移(Enable-Migrations),使用 Add-Migration 创建一个新的迁移文件,将其清空(我的模型已经在数据库中,所以我不希望 EF 尝试创建它们)并部署它。为了进行部署,我将以下内容添加到 Global.asax 文件中:

protected void Application_Start()
{
        var config= new Configuration();
        var migrator = new DbMigrator(config);
        migrator.Update();
}

创建了一个新表 __MigrationHistory,并在其中创建了一个新的迁移记录。这个新的迁移记录包含我的模型的哈希值,因此现在可以在将来使用 EF 进行迁移时为我编写对模型的任何更改的脚本。

为了进行测试,我创建了另一个迁移文件 (Add-Migration),向模型添加了一个新属性,运行了编写新字段脚本的 Add-Migrations,然后部署了我的应用程序。迁移按预期运行。

So it seems what I was looking for is Codebased Migrations which is activated when I set AutomaticMigrationsEnabled=false. My models were generated from an existing database. To activate migrations, all I needed to do was enable migrations (Enable-Migrations), create a new new migration file using Add-Migration, empty it out (my models are already in the database so I don't want EF to try and create them) and deploy that. To deploy, I added the following to my Global.asax file:

protected void Application_Start()
{
        var config= new Configuration();
        var migrator = new DbMigrator(config);
        migrator.Update();
}

A new table __MigrationHistory was created and a new migration record was create in it. This new migration record had a hash of my models so now any changes to my models can be scripted for me in future migrations with EF.

To test, I created another migration file (Add-Migration), I added a new property to a model, ran Add-Migrations which scripted the new field and then deployed my application. The migration was run as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文