2

エンティティ フレームワーク プロジェクトでコード ファーストの移行を有効にし、テーブルの名前変更などを行ういくつかの移行を追加しました。ただし、データベースを削除し、エンティティ フレームワークが最新のデータ モデルに基づいて新しいデータベースを生成するようにしました。実行しようとすると:

PM> Add-Migration TestMigration

...最初に既存の移行を適用する必要があることがわかります。だから私は実行します:

PM> Update-Database

...しかし、問題は、更新する必要のないデータベースを更新しようとしていることです。すでに最新のデータ モデルに基づいています。そのため、現在存在しないテーブルの名前を変更しようとするとエラーが発生します。

データベースが最新であり、移行を実行する必要がないことをデータ移行に示す方法はありますか? 私は何をすべきか?

4

3 に答える 3

9

データベースが最新であることを示す方法を見つけました。これは (当然のことながら)__MigrationHistoryテーブルの変更に基づいており、実行時に DB に適用する移行を決定するためにコード ファースト マイグレーションが使用しますUpdate-Database

ところで、この回答を調査しているときに、コード ファーストの移行コマンドに関する非常に優れたリファレンスを見つけました

データベースが EF によって自動的に最初から作成される場合、常に単一のエントリが__MigrationHistoryテーブルに配置され、そのエントリには MigrationId が含まれ(currentDateTime)_InitialCreateます。これは、EF が実行したばかりのデータベースの最初の作成を表します。ただし、移行履歴はその MigrationId で始まるわけではありません。別のことから始めているからです。

コードファーストの移行を「だまして」、最新の移行を行っていると思わせるには、新しく作成された DB(currentDateTime)_InitialCreateのテーブルからそのエントリを削除し__MigrationHistory、古い DB がまだあった場合にそこにあったであろうものを挿入する必要があります。移行が適用されていました。

したがって、最初に新しく生成された DB の__MigrationHistoryテーブルからすべてを削除します。次に、パッケージ マネージャー コンソールに移動し、次を実行します。

PM> Update-Database -Script

結果の SQL スクリプトから、次で始まるすべての行を取り出します。

INSERT INTO [__MigrationHistory]...

次に、INSERT新しく作成されたデータベースのコンテキスト内でこれらのステートメントを実行します。これらの各行が__MigrationHistoryテーブルに存在することを確認します。次に実行するとき:

PM> Update-Database

...「保留中のコードベースの移行はありません」というメッセージが表示されるはずです。おめでとうございます - コード ファーストの移行をだまして、現在は最新の移行を行っていると思い込ませました。ここから新しい移行を追加して中断したところから続行できます。

EFコードファーストに組み込まれたこれを行う自動化された方法があるはずだと思いますが、おそらく次のようなものを追加する必要があります。

PM> Update-Database -MigrationsTableOnly

...これにより、移行テーブルの既存のエントリが上書きされ、プロジェクトで定義された移行ごとに新しいエントリが移行履歴に挿入されますが、実際に移行を試行して実行することはありません。まぁ。

更新
カスタム初期化子の Seed メソッドを使用して、これをうまく自動化する方法を見つけました。基本的に Seed メソッドは、DB の作成時に既存の移行履歴データを削除し、移行履歴を挿入します。私のデータベース コンテキスト コンストラクターでは、次のようにカスタム初期化子を登録します。

public class MyDatabaseContext : DbContext {
    public MyDatabaseContext() : base() {
        Database.SetInitializer(new MyDatabaseContextMigrationHistoryInitializer());
    }

カスタム初期化子自体は次のようになります。

/// <summary>
/// This initializer clears the __MigrationHistory table contents created by EF code-first when it first
/// generates the database, and inserts all the migration history entries for migrations that have been
/// created in this project, indicating to EF code-first data migrations that the database is
/// "up-to-date" and that no migrations need to be run when "Update-Database" is run, because we're
/// already at the latest schema by virtue of the fact that the database has just been created from
/// scratch using the latest schema.
/// 
/// The Seed method needs to be updated each time a new migration is added with "Add-Migration".  In
/// the package manager console, run "Update-Database -Script", and in the SQL script which is generated,
/// find the INSERT statement that inserts the row for that new migration into the __MigrationHistory
/// table.  Add that INSERT statement as a new "ExecuteSqlCommand" to the end of the Seed method.
/// </summary>
public class MyDatabaseContextMigrationHistoryInitializer : CreateDatabaseIfNotExists<MyDatabaseContext> {
    /// <summary>
    /// Sets up this context's migration history with the entries for all migrations that have been created in this project.
    /// </summary>
    /// <param name="context">The context of the database in which the seed code is to be executed.</param>
    protected override void Seed(MyDatabaseContext context) {
        // Delete existing content from migration history table, and insert our project's migrations
        context.Database.ExecuteSqlCommand("DELETE FROM __MigrationHistory");
        context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210091606260_InitialCreate', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF54AD7E074A..., '5.0.0.net40')");
        context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210102218467_MakeConceptUserIdNullable', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4..., '5.0.0.net40')");
        context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210231418163_ChangeDateTimesToDateTimeOffsets', 0x1F8B0800000000000400ECBD07601C499625262F6D..., '5.0.0.net40')");
        context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210251833252_AddConfigSettings', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF54AD7E..., '5.0.0.net40')");
        context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210260822485_RenamingOfSomeEntities', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF5..., '5.0.0.net40')");
    }
}
于 2012-10-28T10:59:59.507 に答える
0

この実装では、挿入するレコードを手動で維持する必要はありません__MigrationHistory。移行は、指定されたアセンブリから決定されます。

たぶんこれが役立ちます。

最初のアイデアについて@Jezに感謝します。

/// <summary>
/// An implementation of IDatabaseInitializer that will:
/// 1. recreate database only if the database does not exist 
/// 2. actualize __MigrationHistory to match current model state (i.e. latest migration)
/// </summary>
/// <typeparam name="TContext">The type of the context.</typeparam>
public class CreateDatabaseIfNotExistsAndMigrateToLatest<TContext> : CreateDatabaseIfNotExists<TContext>
    where TContext : DbContext
{
    private readonly Assembly migrationsAssembly;

    /// <summary>
    /// Gets the migration metadata for types retrieved from <paramref name="assembly"/>. Types must implement <see cref="IMigrationMetadata"/>.
    /// </summary>
    /// <param name="assembly">The assembly.</param>
    /// <returns></returns>
    private static IEnumerable<IMigrationMetadata> GetMigrationMetadata(Assembly assembly)
    {
        var types = assembly.GetTypes().Where(t => typeof(IMigrationMetadata).IsAssignableFrom(t));
        var migrationMetadata = new List<IMigrationMetadata>();
        foreach (var type in types)
        {
            migrationMetadata.Add(
                (IMigrationMetadata)Activator.CreateInstance(type));
        }

        return migrationMetadata.OrderBy(m => m.Id);
    }

    /// <summary>
    /// Gets the provider manifest token.
    /// </summary>
    /// <param name="db">The db.</param>
    /// <returns></returns>
    private static string GetProviderManifestToken(TContext db)
    {
        var connection = db.Database.Connection;
        var token = DbProviderServices.GetProviderServices(connection).GetProviderManifestToken(connection);

        return token;
    }

    /// <summary>
    /// Gets the migration SQL generator. Currently it is <see cref="SqlServerMigrationSqlGenerator"/>.
    /// </summary>
    /// <returns></returns>
    private static MigrationSqlGenerator GetMigrationSqlGenerator()
    {
        return new SqlServerMigrationSqlGenerator();
    }

    /// <summary>
    /// Creates the operation for inserting into migration history. Operation is created for one <paramref name="migrationMetadatum"/>.
    /// </summary>
    /// <param name="migrationMetadatum">The migration metadatum.</param>
    /// <returns></returns>
    private static InsertHistoryOperation CreateInsertHistoryOperation(IMigrationMetadata migrationMetadatum)
    {
        var model = Convert.FromBase64String(migrationMetadatum.Target);

        var op = new InsertHistoryOperation(
            "__MigrationHistory",
            migrationMetadatum.Id,
            model,
            null);

        return op;
    }

    /// <summary>
    /// Generates the SQL statements for inserting migration into history table.
    /// </summary>
    /// <param name="generator">The generator.</param>
    /// <param name="op">The operation.</param>
    /// <param name="token">The token.</param>
    /// <returns></returns>
    private static IEnumerable<MigrationStatement> GenerateInsertHistoryStatements(
        MigrationSqlGenerator generator,
        InsertHistoryOperation op,
        string token)
    {
        return generator.Generate(new[] { op }, token);
    }

    /// <summary>
    /// Runs the SQL statements on database specified by <paramref name="db"/> (<see cref="DbContext.Database"/>).
    /// </summary>
    /// <param name="statements">The statements.</param>
    /// <param name="db">The db.</param>
    private static void RunSqlStatements(IEnumerable<MigrationStatement> statements, TContext db)
    {
        foreach (var statement in statements)
        {
            db.Database.ExecuteSqlCommand(statement.Sql);
        }
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="CreateDatabaseIfNotExistsAndMigrateToLatest{TContext}"/> class.
    /// </summary>
    /// <param name="migrationsAssembly">The migrations assembly.</param>
    public CreateDatabaseIfNotExistsAndMigrateToLatest(Assembly migrationsAssembly)
    {
        this.migrationsAssembly = migrationsAssembly;
    }

    protected override void Seed(TContext context)
    {
        base.Seed(context);

        // Get migration metadata for migrationAssembly
        var migrationMetadata = GetMigrationMetadata(migrationsAssembly);

        // Crate DbContext
        var db = Activator.CreateInstance<TContext>();
        // Remove newly created record in __MigrationHistory
        db.Database.ExecuteSqlCommand("DELETE FROM __MigrationHistory");

        // Get provider manifest token
        var token = GetProviderManifestToken(db);
        // Get sql generator
        var generator = GetMigrationSqlGenerator();

        foreach (var migrationMetadatum in migrationMetadata)
        {
            // Create history operation
            var op = CreateInsertHistoryOperation(migrationMetadatum);
            // Generate history insert statements
            var statements = GenerateInsertHistoryStatements(generator, op, token);
            // Run statements (SQL) over database (db)
            RunSqlStatements(statements, db);
        }
    }
}
于 2013-07-24T11:25:14.493 に答える
0

MigrationHistorySQLサーバー(フォルダーの下)のテーブルに移動systemします。移行用の行と、移行ファイルの1つと同じでなければならないdbハッシュがあり、dbからファイルにコピーするだけです。

MigrationHistoryつまり、テーブルを実際の移行と同期する必要があります。

于 2012-10-28T09:29:36.367 に答える