自訂遷移歷程記錄資料表Custom Migrations History Table

根據預設,EF Core 會在名為的資料表中記錄,以追蹤已套用至資料庫的遷移 __EFMigrationsHistoryBy default, EF Core keeps track of which migrations have been applied to the database by recording them in a table named __EFMigrationsHistory. 基於各種原因,您可能會想要自訂此資料表,以更符合您的需求。For various reasons, you may want to customize this table to better suit your needs.

重要

如果您在套用遷移 之後 自訂遷移歷程記錄資料表,您必須負責更新資料庫中的現有資料表。If you customize the Migrations history table after applying migrations, you are responsible for updating the existing table in the database.

架構和資料表名稱Schema and table name

您可以使用 MigrationsHistoryTable() (中的方法 OnConfiguring() 或 ASP.NET Core) 來變更架構和資料表名稱 ConfigureServices()You can change the schema and table name using the MigrationsHistoryTable() method in OnConfiguring() (or ConfigureServices() on ASP.NET Core). 以下是使用 SQL Server EF Core 提供者的範例。Here is an example using the SQL Server EF Core provider.

protected override void OnConfiguring(DbContextOptionsBuilder options)
    => options.UseSqlServer(
        connectionString,
        x => x.MigrationsHistoryTable("__MyMigrationsHistory", "mySchema"));

其他變更Other changes

若要設定資料表的其他層面,請覆寫並取代提供者特定的 IHistoryRepository 服務。To configure additional aspects of the table, override and replace the provider-specific IHistoryRepository service. 以下是在 SQL Server 上將 MigrationId 資料行名稱變更為 Id 的範例。Here is an example of changing the MigrationId column name to Id on SQL Server.

protected override void OnConfiguring(DbContextOptionsBuilder options)
    => options
        .UseSqlServer(connectionString)
        .ReplaceService<IHistoryRepository, MyHistoryRepository>();

警告

SqlServerHistoryRepository 位於內部命名空間內部,未來的版本可能會變更。SqlServerHistoryRepository is inside an internal namespace and may change in future releases.

class MyHistoryRepository : SqlServerHistoryRepository
{
    public MyHistoryRepository(HistoryRepositoryDependencies dependencies)
        : base(dependencies)
    {
    }

    protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)
    {
        base.ConfigureTable(history);

        history.Property(h => h.MigrationId).HasColumnName("Id");
    }
}