自訂的移轉作業Custom Migrations Operations

MigrationBuilder API 可讓您在移轉時,執行許多不同種類的作業,但不能完全詳盡。The MigrationBuilder API allows you to perform many different kinds of operations during a migration, but it's far from exhaustive. 不過,此 API 也是可延伸可讓您定義您自己的作業。However, the API is also extensible allowing you to define your own operations. 有兩種方式可延伸 API: 使用Sql()方法,或藉由定義自訂MigrationOperation物件。There are two ways to extend the API: Using the Sql() method, or by defining custom MigrationOperation objects.

為了說明,讓我們看看實作建立資料庫使用者,使用每一種方法的作業。To illustrate, let's look at implementing an operation that creates a database user using each approach. 在我們的移轉,我們想要啟用寫入下列程式碼:In our migrations, we want to enable writing the following code:

migrationBuilder.CreateUser("SQLUser1", "Password");

使用 MigrationBuilder.Sql()Using MigrationBuilder.Sql()

實作自訂作業的最簡單方式是定義擴充方法呼叫MigrationBuilder.Sql()The easiest way to implement a custom operation is to define an extension method that calls MigrationBuilder.Sql(). 以下是範例會產生適當的 Transact SQL。Here is an example that generates the appropriate Transact-SQL.

static MigrationBuilder CreateUser(
    this MigrationBuilder migrationBuilder,
    string name,
    string password)
    => migrationBuilder.Sql($"CREATE USER {name} WITH PASSWORD '{password}';");

如果您的移轉需要支援多個資料庫提供者,您可以使用MigrationBuilder.ActiveProvider屬性。If your migrations need to support multiple database providers, you can use the MigrationBuilder.ActiveProvider property. 以下是支援 Microsoft SQL Server 和 PostgreSQL 的範例。Here's an example supporting both Microsoft SQL Server and PostgreSQL.

static MigrationBuilder CreateUser(
    this MigrationBuilder migrationBuilder,
    string name,
    string password)
{
    switch (migrationBuilder.ActiveProvider)
    {
        case "Npgsql.EntityFrameworkCore.PostgreSQL":
            return migrationBuilder
                .Sql($"CREATE USER {name} WITH PASSWORD '{password}';");

        case "Microsoft.EntityFrameworkCore.SqlServer":
            return migrationBuilder
                .Sql($"CREATE USER {name} WITH PASSWORD = '{password}';");
    }

    return migrationBuilder;
}

這個方法僅適用於您知道每個提供者將會套用您的自訂作業。This approach only works if you know every provider where your custom operation will be applied.

使用 MigrationOperationUsing a MigrationOperation

將它們分開自訂的作業,從 SQL,您可以定義您自己MigrationOperation來代表它。To decouple the custom operation from the SQL, you can define your own MigrationOperation to represent it. 作業接著會傳遞至提供者,因此可以判斷適當的 SQL 來產生。The operation is then passed to the provider so it can determine the appropriate SQL to generate.

class CreateUserOperation : MigrationOperation
{
    public string Name { get; set; }
    public string Password { get; set; }
}

使用此方法時,擴充方法只需要新增至這些作業的其中一個MigrationBuilder.OperationsWith this approach, the extension method just needs to add one of these operations to MigrationBuilder.Operations.

static MigrationBuilder CreateUser(
    this MigrationBuilder migrationBuilder,
    string name,
    string password)
{
    migrationBuilder.Operations.Add(
        new CreateUserOperation
        {
            Name = name,
            Password = password
        });

    return migrationBuilder;
}

此方法需要知道如何產生 SQL,這項作業中的每個提供者其IMigrationsSqlGenerator服務。This approach requires each provider to know how to generate SQL for this operation in their IMigrationsSqlGenerator service. 以下是覆寫可處理新作業的 SQL Server 的產生器的範例。Here is an example overriding the SQL Server's generator to handle the new operation.

class MyMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator
{
    public MyMigrationsSqlGenerator(
        MigrationsSqlGeneratorDependencies dependencies,
        IMigrationsAnnotationProvider migrationsAnnotations)
        : base(dependencies, migrationsAnnotations)
    {
    }

    protected override void Generate(
        MigrationOperation operation,
        IModel model,
        MigrationCommandListBuilder builder)
    {
        if (operation is CreateUserOperation createUserOperation)
        {
            Generate(createUserOperation, builder);
        }
        else
        {
            base.Generate(operation, model, builder);
        }
    }

    private void Generate(
        CreateUserOperation operation,
        MigrationCommandListBuilder builder)
    {
        var sqlHelper = Dependencies.SqlGenerationHelper;
        var stringMapping = Dependencies.TypeMappingSource.FindMapping(typeof(string));

        builder
            .Append("CREATE USER ")
            .Append(sqlHelper.DelimitIdentifier(operation.Name))
            .Append(" WITH PASSWORD = ")
            .Append(stringMapping.GenerateSqlLiteral(operation.Password))
            .AppendLine(sqlHelper.StatementTerminator)
            .EndCommand();
    }
}

取代更新的一個預設移轉 sql 產生器服務。Replace the default migrations sql generator service with the updated one.

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