如何在 EF Core Code First 中自定义迁移生成?

How to customize migration generation in EF Core Code First?

我的 DbContext 中有一个特殊的基础 table 类型。当从它继承时,我需要生成一个额外的“SQL”迁移操作来为它创建一个特定的触发器。它通过检查重叠范围确保 table 结构一致。由于 SQL 服务器中没有重叠索引或检查约束,我必须使用触发器(在检查约束中使用函数会导致与迁移相同的问题以及 SQL 中混乱的函数“命名空间”)。

由于在 OnModelCreating 期间我没有找到任何创建触发器的方法,所以我想到了更改生成的迁移。但是要怎么做呢?

尝试使用 SqlServerMigrationsSqlGeneratorSqlServerMigrationsAnnotationProvider,但顾名思义,它们仅在生成 SQL 命令期间的最后阶段使用。这使得它们在使用迁移时有点“隐藏”在视线之外。难以在需要时定制并在事后维护。

考虑过使用 CSharpMigrationOperationGenerator,这似乎非常适合我的需要。但是有一个问题 - 我无法访问这个 class。也不是命名空间。

根据来源,此 class 驻留在 Microsoft.EntityFrameworkCore.Migrations.Design 命名空间中并且是 public。为了访问它,必须安装 Microsoft.EntityFrameworkCore.Design 包。

但是没用。

我在这里错过了什么?如何访问和继承这个class?或者也许有更好更合适的方法在特定 tables 的迁移过程中自动创建触发器?

打开您的迁移文件并更改您的 Up 方法。

然后使用 Update-Database 从程序包管理器控制台应用迁移。

像这样:

public partial class CreateDatabase : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql("Some custom SQL statement");
        migrationBuilder.CreateTable(
            name: "Authors",
            columns: table => new
            {
                AuthorId = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                FirstName = table.Column<string>(nullable: true),
                LastName = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Authors", x => x.AuthorId);
            });
    }
}

如何提供您自己的 ICSharpMigrationOperationGenerator 实施

Thought about using CSharpMigrationOperationGenerator which seems to be perfect for my needs. But there is a problem - I can't access this class. Nor it's namespace.

According to source this class resides in Microsoft.EntityFrameworkCore.Migrations.Design namespace and is public. And in order to access it a Microsoft.EntityFrameworkCore.Design package has to be installed.

But it doesn't work.

What am I missing here? How to access and inherit this class?

假设您在设计时调用以下 CLI 命令来添加新的迁移:

dotnet ef migrations add "SomeMigration"

这是一个完整的示例控制台程序,它将使用一个名为 MyCSharpMigrationOperationGenerator 的自定义 ICSharpMigrationOperationGenerator 实现,继承自 CSharpMigrationOperationGenerator:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Design;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace IssueConsoleTemplate
{
    public class MyCSharpMigrationOperationGenerator : CSharpMigrationOperationGenerator
    {
        public MyCSharpMigrationOperationGenerator(CSharpMigrationOperationGeneratorDependencies dependencies)
            : base(dependencies)
        {
        }

        protected override void Generate(CreateTableOperation operation, IndentedStringBuilder builder)
        {
            Console.WriteLine("\r\n\r\n---\r\nMyCSharpMigrationOperationGenerator was used\r\n---\r\n");
            base.Generate(operation, builder);
        }
    }
    
    public class MyDesignTimeServices : IDesignTimeServices
    {
        public void ConfigureDesignTimeServices(IServiceCollection services)
            => services.AddSingleton<ICSharpMigrationOperationGenerator, MyCSharpMigrationOperationGenerator>();
    }
    
    public class IceCream
    {
        public int IceCreamId { get; set; }
        public string Name { get; set; }
    }
    
    public class Context : DbContext
    {
        public DbSet<IceCream> IceCreams { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseSqlServer(@"Data Source=.\MSSQL14;Integrated Security=SSPI;Initial Catalog=So63575132")
                .UseLoggerFactory(
                    LoggerFactory.Create(
                        b => b
                            .AddConsole()
                            .AddFilter(level => level >= LogLevel.Information)))
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }
    }

    internal static class Program
    {
        private static void Main()
        {
        }
    }
}

MyCSharpMigrationOperationGenerator class 为每个添加的 table 输出以下行以证明它被调用:

---
MyCSharpMigrationOperationGenerator was used
---

正如@KasbolatKumakhov 在他的评论中指出的那样,还应该指出从 2.2 引用 Microsoft.EntityFrameworkCore.Design has been changed 的方式。到 3.0:

Starting with EF Core 3.0, it is a DevelopmentDependency package. This means that the dependency won't flow transitively into other projects, and that you can no longer, by default, reference its assembly. [...] If you need to reference this package to override EF Core's design-time behavior, then you can update PackageReference item metadata in your project.

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0">
  <PrivateAssets>all</PrivateAssets>
  <!-- Remove IncludeAssets to allow compiling against the assembly -->
  <!--<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>-->
</PackageReference>

如何正确实施额外的 MigrationOperation(例如用于创建触发器)

Since I haven't found any way to create triggers during OnModelCreating I thought of altering generated migrations. But how to do that?

要正确执行此操作,您需要执行以下操作:

  • 将您自己的注释添加到有问题的 table 中(例如 MyPrefix:Trigger
  • 实现您自己的 MigrationOperation(例如 CreateTriggerMigrationOperation
  • 提供您自己的 IMigrationsModelDiffer 实现(源自 MigrationsModelDiffer;这是内部的)returns 您自己的 MigrationOperation
  • 提供您自己的 ICSharpMigrationOperationGenerator 实现(派生自 CSharpMigrationOperationGenerator),然后为您自己的 MigrationOperation
  • 生成 C# 代码
  • 提供您自己的 IMigrationsSqlGenerator 实现(源自 SqlServerMigrationsSqlGenerator),然后处理将您自己的 MigrationOperation 翻译成 SQL

我认为不是为了修改ef core csharp代码生成。 但是为了生成自定义迁移语句(在我的例子中是触发器),我使用 SqlOperation 执行以下操作(缩短为相关)。

实施模型差异化

public class MyMigrationsModelDiffer : MigrationsModelDiffer {

  public MyMigrationsModelDiffer(IRelationalTypeMappingSource typeMappingSource,
    IMigrationsAnnotationProvider migrationsAnnotations,
    IChangeDetector changeDetector,
    IUpdateAdapterFactory updateAdapterFactory,
    CommandBatchPreparerDependencies commandBatchPreparerDependencies)
    : base(typeMappingSource, migrationsAnnotations, changeDetector, updateAdapterFactory, commandBatchPreparerDependencies) { }

  protected override IEnumerable<MigrationOperation> Diff(IModel source, IModel target, DiffContext diffContext) {
    return base.Diff(source, target, diffContext).Concat(GetTriggerTriggerDifferences(source, target));
  }

  public override Boolean HasDifferences(IModel source, IModel target) {
    return base.HasDifferences(source, target) || HasTriggerAnnotationDifferences(source, target);
  }

  public IEnumerable<MigrationOperation> GetTriggerTriggerDifferences(IModel source, IModel target) {
    if (source == null || target == null) {
      return new new List<MigrationOperation>(0);
    }

    Dictionary<String, IAnnotation> triggerAnnotationPerEntity = new Dictionary<String, IAnnotation>();
    foreach (var entityType in source.GetEntityTypes()) {
      triggerAnnotationPerEntity[entityType.Name] = GetTableAnnotation(entityType);
    }
    var operations = new List<MigrationOperation>();
    foreach (var entityType in target.GetEntityTypes()) {
      triggerAnnotationPerEntity.TryGetValue(entityType.Name, out IAnnotation sourceTriggerTable);
      IAnnotation targetTriggerTable = GetTableAnnotation(entityType);

      if (targetTriggerTable?.Value == sourceTriggerTable?.Value) {
        continue;
      }

      Boolean isCreate = targetTriggerTable != null;
      String tableName = (entityType as EntityType)?.GetTableName();
      String primaryKey = entityType.FindPrimaryKey().Properties[0].Name;
      if (isCreate) {
        SqlOperation sqlOperation = new SqlOperation();
        sqlOperation.Sql = $@"CREATE TRIGGER...";
        operations.Add(sqlOperation);
      }
      else {
        // drop trigger sqloperation
      }
    }
    return operations;
  }

  private static IAnnotation GetTableAnnotation(IEntityType entityType) {
    return entityType.GetAnnotations()?.FirstOrDefault(x => x.Name == "WantTrigger");
  }

  public Boolean HasTriggerAnnotationDifferences(IModel source, IModel target) {
    return GetTriggerTriggerDifferences(source, target).Any();
  }
}

替换与您的 DbContext 不同的模型

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
  base.OnConfiguring(optionsBuilder);
  if (optionsBuilder == null) {
    return;
  }
  optionsBuilder.ReplaceService<IMigrationsModelDiffer, MyMigrationsModelDiffer>();
}

用注释标记所需的模型。

builder.Entity<MyTable>().HasAnnotation("WantTrigger", "1.0");

这与您要求的不完全一样,但它以低成本完成类似的工作,可能对某些人派上用场。

using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;

public static class MigrationBuilderExtensions
{
    public static void ConfigForOracle(this MigrationBuilder migrationBuilder)
    {
        //For each table registered in the builder, let's create a sequence and a trigger
        foreach (CreateTableOperation createTableOperation in migrationBuilder.Operations.ToArray().OfType<CreateTableOperation>())
        {
            string tableName = createTableOperation.Name;
            string primaryKey = createTableOperation.PrimaryKey.Columns[0];
            migrationBuilder.CreateSequence<int>(name: $"SQ_{tableName}", schema: createTableOperation.Schema);
            migrationBuilder.Sql($@"CREATE OR REPLACE TRIGGER ""TR_{tableName}""
                                    BEFORE INSERT ON ""{tableName}""
                                    FOR EACH ROW
                                    WHEN (new.""{primaryKey}"" IS NULL)
                                    BEGIN
                                        SELECT ""SQ_{tableName}"".NEXTVAL
                                        INTO   :new.""{primaryKey}""
                                        FROM   dual;
                                    END;");
        }
    }
}

你可以在扩展方法中做任何你想做的事情,然后在Migration.Up()方法的末尾调用它。我用它为标识符增量的 Oracle 11g 表创建序列和触发器。