自訂的移轉作業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. 不過,應用程式開發介面也是可延伸可讓您定義您自己的作業。However, the API is also extensible allowing you to define your own operations. 有兩種方式來擴充應用程式開發介面: 使用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 和 PostreSQL 範例。Here's an example supporting both Microsoft SQL Server and PostreSQL.

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}';");
    }
}

這個方法只有您知道每個提供者將會套用您的自訂作業。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.TypeMapper.GetMapping(typeof(string));

        builder
            .Append("CREATE USER ")
            .Append(sqlHelper.DelimitIdentifier(name))
            .Append(" WITH PASSWORD = ")
            .Append(stringMapping.GenerateSqlLiteral(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>();