【问题标题】:EF Core 2 cross database migrationsEF Core 2 跨数据库迁移
【发布时间】:2018-06-19 02:02:03
【问题描述】:

我正在尝试使用 EF Core 2.0 创建跨数据库迁移

当我在办公室时,我使用与团队共享的 sql server 数据库来工作。出于这个原因,代码使用了引用 sql server 提供程序的配置

optionsBuilder.UseSqlServer(connectionString, serverOptions => {
    serverOptions.MigrationsHistoryTable("__EFMigrations", "dbo");
});

创建新迁移时,这会使迁移代码使用 sql server 提供程序的特定配置,例如

migrationBuilder.CreateTable(
    name: "Customers",
    schema: "dbo",
    columns: table => new
    {
        EntityID = table.Column<int>(nullable: false)
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
        Name = table.Column<string>(maxLength: 255, nullable: false)
    },
    constraints: table => {
        table.PrimaryKey("PK_Customers", x => x.EntityID);
    });

请注意Annotation 方法。

当我不在办公室时,我使用的是安装在我的 mac 上的 postgreSQL 实例,我需要使用特定的 postgreSQL 提供程序进行稍微不同的迁移

.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),

我知道我可以手动修改迁移以指定两个注释,因为这在特定数据库类型上运行时没有影响。

但是,我希望避免手动修改迁移是一项乏味且容易出错的工作。

有没有办法让EF自动生成这两种Annotation方法?

我还尝试通过在 ModelBuilder 上指定选项来使用 DbContext OnModelCreating 方法

modelBuilder
    .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
    .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

modelBuilder.ForNpgsqlUseSerialColumns();
modelBuilder.ForSqlServerUseIdentityColumns();

但生成的迁移总是与特定时刻使用的提供程序相关。

【问题讨论】:

    标签: entity-framework entity-framework-core entity-framework-migrations ef-core-2.0 cross-database


    【解决方案1】:

    没有办法让 EF Core 为你做这件事。你正在做的是最好的方法。一种稍微不那么繁琐的方法是保留两组独立的迁移——每个提供者一个。

    更多详情请见EF Core Migrations with Multiple Providers

    【讨论】:

    • 感谢您的回答。我完全错过了链接页面。另外,我认为创建从 DbContext 派生的新类型的方法可能是一个很好的让步。有趣的是,您回答了这个问题并与链接的帖子合作:这绝对意味着我得到了最好的答案:)
    • 大声笑,我为 EF Core 迁移编写了代码。我不知道这是否是最好的答案,但我当然希望这是一个好的答案。 ;-)
    猜你喜欢
    • 2019-08-03
    • 1970-01-01
    • 2022-09-29
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多