如何覆盖默认的 SQL 迁移生成器?

How does one override the default SQL migration generator?

我正在尝试覆盖 SQL 迁移生成器的默认行为,以便我可以指定自定义外键约束名称,如 所述。我已经按照建议连接了配置。

然而不幸的是,进展并不顺利。

快速记录语句显示 GetFkName() 函数从未被命中。

我尝试了另一种配置构造,如 here and here 所讨论的那样,但是当我尝试生成迁移时遇到此错误:

More than one migrations configuration type was found in the assembly 'ConsoleApp1'. Specify the name of the one to use.

我觉得这个结果有点奇怪,因为我只有一个配置class、一个SQL代class和一个上下文class(下面的代码没有反映这一点,但我为我的实际测试注释掉了额外的内容)。在命令行指定配置类型,如所示,错误为:

System.InvalidOperationException: The type 'ConsoleApp1.Db.CustomDbConfiguration2' does not inherit from 'System.Data.Entity.DbConfiguration'. Entity Framework code-based configuration classes must inherit from 'System.Data.Entity.DbConfiguration'.

所有这些都让我们回到 ,然后,由于上述原因,这不起作用(GetFkName() 永远不会被击中)。所以我好像在追我的尾巴(直到今天才知道我有尾巴)。

我应该怎么做才能使此覆盖正常工作?


配置

Imports System.Data.Entity
Imports System.Data.Entity.Migrations
Imports System.Data.Entity.SqlServer

Namespace Db
  Friend Class CustomDbConfiguration
    Inherits DbConfiguration

    Public Sub New()
      Me.SetMigrationSqlGenerator(SqlProviderServices.ProviderInvariantName, Function() New CustomSqlGenerator)
    End Sub
  End Class

  Friend Class CustomDbConfiguration2
    Inherits DbMigrationsConfiguration(Of Context)

    Public Sub New()
      Me.SetSqlGenerator(SqlProviderServices.ProviderInvariantName, New CustomSqlGenerator2(Me.GetSqlGenerator(SqlProviderServices.ProviderInvariantName)))
      Me.ContextType = GetType(Context)
    End Sub
  End Class
End Namespace

SQL 发电机

Imports System.Data.Entity.Migrations.Model
Imports System.Data.Entity.Migrations.Sql
Imports System.Data.Entity.SqlServer

Namespace Db
  Friend Class CustomSqlGenerator
    Inherits SqlServerMigrationSqlGenerator

    Protected Overrides Sub Generate(AddForeignKeyOperation As AddForeignKeyOperation)
      AddForeignKeyOperation.Name = GetFkName(AddForeignKeyOperation.PrincipalTable, AddForeignKeyOperation.DependentTable, AddForeignKeyOperation.DependentColumns.ToArray())
      MyBase.Generate(AddForeignKeyOperation)
    End Sub

    Protected Overrides Sub Generate(DropForeignKeyOperation As DropForeignKeyOperation)
      DropForeignKeyOperation.Name = GetFkName(DropForeignKeyOperation.PrincipalTable, DropForeignKeyOperation.DependentTable, DropForeignKeyOperation.DependentColumns.ToArray())
      MyBase.Generate(DropForeignKeyOperation)
    End Sub

    Private Shared Function GetFkName(PrimaryKeyTable As String, ForeignKeyTable As String, ParamArray ForeignTableFields As String()) As String
      IO.File.WriteAllText("D:\Logs\FkNameTest.log", $"{Now.ToString}{vbCrLf}")

      Return $"FK_{ForeignKeyTable}_{PrimaryKeyTable}"
    End Function
  End Class

  Friend Class CustomSqlGenerator2
    Inherits MigrationSqlGenerator

    Public Sub New(Generator As MigrationSqlGenerator)
      Me.Generator = Generator
    End Sub

    Public Overrides Function Generate(MigrationOperations As IEnumerable(Of MigrationOperation), ProviderManifestToken As String) As IEnumerable(Of MigrationStatement)
      Return Me.Generator.Generate(MigrationOperations, ProviderManifestToken)
    End Function

    Private ReadOnly Generator As MigrationSqlGenerator
  End Class
End Namespace

上下文

Imports System.Data.Common
Imports System.Data.Entity
Imports System.Data.SqlClient
Imports System.Reflection

Namespace Db
  <DbConfigurationType(GetType(CustomDbConfiguration2))>
  Friend Class Context
    Inherits DbContext

    Public Sub New()
      MyBase.New(DbConnection.ConnectionString)
    End Sub

    Private Sub New(Connection As DbConnection)
      MyBase.New(Connection, True)

      Database.SetInitializer(New CreateDatabaseIfNotExists(Of Context))
      Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of Context, Migrations.Configuration))

      Me.Database.Initialize(False)
    End Sub

    Public Shared Function Create() As Context
      Return New Context(DbConnection)
    End Function

    Private Shared ReadOnly Property DbConnection As SqlConnection
      Get
        Return New SqlConnection(Utils.DbConnectionString)
      End Get
    End Property

    Protected Overrides Sub OnModelCreating(Builder As DbModelBuilder)
      Builder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly)
      MyBase.OnModelCreating(Builder)
    End Sub

    Public Property Documents As DbSet(Of Document)
    Public Property Sections As DbSet(Of Section)
  End Class
End Namespace

Disclaimer: I haven't coded in VB for many years, these code examples are my feeble attempt to translate my working example in C# into OPs native VB. Please feel free to update my syntax ;)

您可以手动编辑迁移脚本,通过在调用中为可选的 Name 参数指定一个值,为每个 ForeignKey 指定一个 自定义 名称Tablebuilder.ForeignKey 作为 create table 语句的一部分:

CreateTable(
  "dbo.CorporationVariety",
  Function(c) New With
    {
      .Id = c.Int(nullable: false, identity:= true),
      .CorporationId = c.Int(nullable:= false),
      .VarietyId = c.Int(nullable:= false),
    }) _
  .PrimaryKey(Function(t) t.Id)
  .ForeignKey("dbo.Corporation", Function(t) t.CorporationId, name := "FKCorporatationCorporationVarietyCorporationId")
  .ForeignKey("dbo.Variety", Function(t) t.VarietyId, name := "FKVarietyCorporationVarietyVarietyId")
  .Index(Function(t) t.CorporationId)
  .Index(Function(t) t.VarietyId)

或作为 DbMigration.AddForeignKey 语句的一部分:

AddForeignKey("dbo.CorporationVariety", "CorporationId", "dbo.Corporation", name := "FKCorporatationCorporationVarietyCorporationId")
AddForeignKey("dbo.CorporationVariety", "VarietyId", "dbo.Variety", name := "FKVarietyCorporationVarietyVarietyId")

如果您的模型中有很多键,并且您想要实现特定的约定,(作为标准规则或代码序列如果您想在给定场景) 中应用所有键,那么通常 寻找解决方案的第一个地方是EF Code First Conventions.

不幸的是,这里既没有可以帮助您的标准约定,也不能使用流利的表示法为外键定义自定义名称...

Normally we would go ahead and create a Custom Code First Convention to define your custom logic, this works in generally 2 ways:

  1. Your convention executes standard configuration via Fluent Notation
    • we already noted that this option is not available to us...
  2. Your convention logic stores custom metadata to the model via annotations

Primary and Foreign keys seem to be an anomaly in the EF Code First Runtime, there does not seem to be a way to easily access the annotations from the associations even though they are relatively easy to define.

I was surprised to find this and stumbled across this post that further confirms this:

Update 我开始这个 post 假设 Conventions 是正确的方法,因为我将它用于许多多年来我需要应用的其他定制。如果您希望实现其他类似类型的自定义,请先查看 Conventions

我们仍然可以轻松覆盖生成迁移代码文件的标准 VisualBasicMigrationCodeGenerator,所以让我们直接跳到那个。 coapply to custom name for your ForeignKey and then implement a custom MigrationCodeGenerator 来处理约定的输出。

  1. 创建自定义 VisualBasicMigrationCodeGenerator
  2. 注册代码生成器,以便 EF 使用它生成下一个迁移

NOTE: This will not force existing keys in your database to be renamed. To do that you would need to force each key to be dropped and re-added back. For a large model Consider using a T4 template to create custom once-off migration logic to achieve this, once the above steps are in place.

Think of your Custom VisualBasicMigrationCodeGenerator as your personal EF code first sour dough culture, you can share this and re-use it for every new application, adding new functionality and improvements with each iteration. But Conventions are the configuration options that you may not want in every project, (which is why using _Conventions_ for OPs solution was my first direction.)

1。创建自定义 VisualBasicMigrationCodeGenerator

创建一个继承自 EF VisualBasicMigrationCodeGenerator 的新 class,我们至少需要覆盖 AddForeignKeyOperation 并修改 键的名称 并调用基本实现。这将影响添加到模型的所有新键。

要定位作为 CreateTable 的一部分添加的键,我们将不得不覆盖 GenerateInline(AddForeignKeyOperation...),但是基本实现(在 C# 生成器中...)不会遵守习俗 Name 所以我们必须完全替换实现。

  • 执行此操作时,转到 EF project on GitHub 并从原始实现开始,然后根据需要注入自定义项。

Please excuse this C#, I didn't have time to translate it, it does generate the correct VB code though ;)

public class CustomVBMigrationCodeGenerator : System.Data.Entity.Migrations.Design.VisualBasicMigrationCodeGenerator
{

    protected override void Generate(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer)
    {
        ApplyCustomFKName(addForeignKeyOperation);
        base.Generate(addForeignKeyOperation, writer);
    }

    private void ApplyCustomFKName(ForeignKeyOperation operation)
    {
        // expecting FK without scheme or underscores: "FK{DependentTable}{PrincipalTable}{FKField}"
        operation.Name = $"FK{StripSchemeFromName(operation.DependentTable)}{StripSchemeFromName(operation.PrincipalTable)}{String.Join("", operation.DependentColumns)}";
    }
    private string StripSchemeFromName(string dbObjectName)
    {
        return dbObjectName.Split(new[] { '.' }, 2).Last();
    }

    /// <summary>
    /// Generates code to perform an <see cref="AddForeignKeyOperation" /> as part of a <see cref="CreateTableOperation" />.
    /// </summary>
    /// <param name="addForeignKeyOperation"> The operation to generate code for. </param>
    /// <param name="writer"> Text writer to add the generated code to. </param>
    protected virtual void GenerateInline(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer)
    {
        // sourced from https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/Migrations/Design/VisualBasicMigrationCodeGenerator.cs
        Check.NotNull(addForeignKeyOperation, "addForeignKeyOperation");
        Check.NotNull(writer, "writer");

        writer.WriteLine(" _");
        writer.Write(".ForeignKey(" + Quote(addForeignKeyOperation.PrincipalTable) + ", ");
        Generate(addForeignKeyOperation.DependentColumns, writer);

        // Our Custom logic
        ApplyCustomFKName(addForeignKeyOperation);

        // Insert our custom name if provided
        if (!addForeignKeyOperation.HasDefaultName)
        {
            writer.Write(", name := " + Quote(addForeignKeyOperation.Name));
        }

        if (addForeignKeyOperation.CascadeDelete)
        {
            writer.Write(", cascadeDelete := True");
        }

        writer.Write(")");
    }
}

2。注册代码生成器,以便 EF 使用它生成下一个迁移

在您的项目中找到 Configuration.vb,构造函数将 CodeGenerator 设置为您的 CustomVBMigrationCodeGenerator 的实例:

Public Sub New()

  AutomaticMigrationsEnabled = false
  CodeGenerator = new CustomVBMigrationCodeGenerator()

End Sub

现在执行 add-migration 以生成新的迁移,您将看到在迁移脚本中定义的新自定义名称。

如果您需要从此配置降级_或者_如果更改table命令需要先删除密钥,您可能还需要类似地覆盖Generate(DropForeignKeyOperation...)方法.