6

我正在考虑将Entity Framework 6 Code First数据库交互与DbUp数据库模式更新一起使用。问题是我不想使用EF迁移是有原因的。所以,我已经达到的工作流程是:

  1. 更改模型(添加POCO、更改属性等)
  2. Add-Migration temp_file进去Visual Studio Package Manager Console
  3. Update-Database -Script进去Visual Studio Package Manager Console
  4. 抓取生成的sql脚本,包括在表中插入新行__MigrationHistory
  5. 创建一个新.sql文件并过去生成的脚本
  6. 删除temp_file
  7. 运行 DbUp

temp_file它在本地和生产服务器上完美运行,但是每次生成新迁移时我都对添加然后删除感到不舒服(我希望有一种方法可以永久停止temp_file添加到解决方案中。)。

所以问题: 有没有更好的方法来DbUp使用 using进行数据库迁移Entity Framework

4

2 回答 2

4

在大多数情况下,您可以利用Automatic Code First Migrations跳过步骤 (2) 和 (6) :

Automatic Migrations 允许您使用 Code First Migrations ,而无需在您的项目中为您所做的每个更改创建一个代码文件

默认情况下,自动迁移被禁用。您可以通过在 db 迁移配置类构造函数(通常调用Configuration并位于Migrations子文件夹下)中添加以下内容来启用它们:

AutomaticMigrationsEnabled = true;

需要考虑的一些事项:

  • 文档指出自动迁移有局限性,因此请注意。
  • 您可以混合使用自动迁移和基于代码的迁移(换句话说,建议的方法和您当前的方法)。
  • The benefits of your current approach is that you can preview how EF interprets your model changes and also add/remove/change parts of the migration code.
  • The automatic migrations have been deprecated (don't exist) in EF Core, so in EF Core projects you have to use something similar to your current approach, except that you have to keep the generated migration code files.
于 2018-01-30T10:28:06.840 回答
2

Maybe this answer is too late, but maybe it will be useful as well. I completely understand your approach to use Entity Framework as ORM and a different tool for schema migration. But choosing DbUp requires you to write manually SQL or generate them as you described above. I suggest considering to use FluentMigrator instead of DbUp. It follows the same philosophy, but allows writing migration steps in C# using fluent syntax. In addition, it supports downgrades, i.e. rollback.

Here is an example:

[Migration(1)]
public class CreateUserTable : Migration
{
    public override void Up()
    {
        Create.Table("Users");
    }

    public override void Down()
    {
        Delete.Table("Users");
    }
}
于 2018-02-05T21:53:34.140 回答