自訂的移轉歷程記錄資料表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()(或ConfigureServices()ASP.NET Core 上)。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. 以下是變更的 MigrationId 資料行名稱的範例識別碼SQL Server 上。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");
    }
}