将Postgres db转换为迁移

时间:2020-03-29 03:17:49

标签: postgresql asp.net-core .net-core fluent-migrator

我有一个继承的数据库,并希望将数据库本身转换为可在ASP.NET Core 3 API中使用的迁移。如果可以的话,我希望不必手动编写迁移,而是将数据库转换为迁移。

我知道使用Entity Framework Core非常容易,但是出于性能原因以及个人喜好,我希望使用dapper而不是EF。

我已经探索并接触了两个与Postgres兼容的迁移管理库:Fluent Migrator和Evolve。

在从现有数据库进行迁移的过程中,是否有人对这两种方法有任何经验?

谢谢

1 个答案:

答案 0 :(得分:0)

我是FluentMigrator的维护者。我从未听说过Evolve,但是我看到的其他框架包括db-up,RoundhousE和SharpMigrations。由于FluentMigrator已经存在了十多年,因此它可能具有所有数据库迁移框架中最完整的即用型功能集。我以前使用RoundhousE,但发现它引起的问题比解决的问题多。

FluentMigrator不会为您“生成”迁移。您必须自己编写。相比之下,Entity Framework Core可以使用其流畅的模型构建语法并自动推断上/下迁移,而您可以主要专注于编写数据迁移。

也就是说,与FluentMigrator中的相同逻辑相比,这是Microsoft建议使用EFCore编写迁移的方式:

EFCore

来源:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations?view=aspnetcore-3.1#examine-up-and-down-methods

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Course",
            columns: table => new
            {
                CourseID = table.Column<int>(nullable: false),
                Credits = table.Column<int>(nullable: false),
                Title = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Course", x => x.CourseID);
            });

        // Additional code not shown
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Enrollment");
        // Additional code not shown
    }
}

FluentMigrator

public class InitialCreate : Migration
{
    public void Up()
    {
        Create.Table("Course")
                .WithColumn("CourseID").AsInt32().NotNullable().PrimaryKey()
                .WithColumn("Credits").AsInt32().NotNullable()
                .WithColumn("Title").AsString().Nullable();

        // Additional code not shown
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        Delete.Table("Enrollment");
        // Additional code not shown
    }
}

在上面的示例中,您不需要在主键定义中键入PK_Course,因为FluentMigrator通过命名约定和正确的名称“知道”支持“不要重复自己”原理为您的主键。您只需定义一次命名约定即可。

此外,由于语法流利,您将发现输入的内容比使用EFCore迁移时要少得多。如果您发现情况并非如此,请提供反馈,我们将使其更加有效。

相关问题