如何使用带有Code First Migrations的Fluent API设置外键名称?

问题描述 投票:0回答:2

我正在尝试使用EF6.4上的Code First Migrations设置外键名称(而不是外键列)。​​>

我知道可以通过更新生成的迁移代码来进行设置,例如:

.ForeignKey("Documents", Function(t) t.DocumentId, cascadeDelete:=True, name:="FK_Sections_Documents")

...但是我想使用Fluent API在添加迁移之前进行。

我似乎想起了有关HasForeignKey()调用的一些事情,该调用接受Func,该调用在其主体中包含对匿名类型的调用,例如我们发现的here。但是如果我能找到任何讨论该类型的一般结构的东西,我会很惊讶。

官方文档中没有讨论:

我正在使用EntityTypeConfiguration(Of T)。这是我的代码:

Namespace Configuration
  Friend Class SectionConfig
    Inherits EntityTypeConfiguration(Of Db.Section)

    Public Sub New()
      Me.HasRequired(Function(Section) Section.Document).WithMany.HasForeignKey(Function(Section) Section.DocumentId)

      Me.Property(Function(Section) Section.DocumentId).IsRequired()
      Me.Property(Function(Section) Section.SectionId).IsRequired()
      Me.Property(Function(Section) Section.IsSent).IsRequired()
      Me.Property(Function(Section) Section.Markup).IsRequired.IsMaxLength()
      Me.Property(Function(Section) Section.Title).IsRequired.HasMaxLength(60)

      Me.HasIndex(Function(Section) Section.DocumentId).HasName("IX_Sections_DocumentId")
      Me.HasIndex(Function(Section) Section.SectionId).HasName("IX_Sections_SectionId")
      Me.HasIndex(Function(Section) Section.Title).HasName("IX_Sections_Title")

      Me.Ignore(Function(Section) Section.Subject)
    End Sub
  End Class
End Namespace

[如何设置外键名称,或者更确切地说,假设我没记错的话,该匿名类型的一般结构应该是什么?

-UPDATE-

我尝试过:

Me.HasRequired(Function(Section) Section.Document).WithMany.HasForeignKey(Function(Section) New With {.DependentKeyExpression = Section.DocumentId, .Name = "FK_Sections_Documents"})

...但是创建迁移的尝试对此进行了回答:

System.Reflection.TargetInvocationException:调用的目标引发了异常。 ---> System.InvalidOperationException:属性表达式'Section => new VB $ AnonymousType_0`2(DependentKeyExpression = Section.DocumentId,Name =“ FK_Sections_Documents”)'是无效的。该表达式应表示一个属性:C#:'t => t.MyProperty'VB.Net:'Function(t)t.MyProperty'。当指定多个属性时,请使用匿名类型:C#:'t => new {t.MyProperty1,t.MyProperty2}'VB.Net:'Function(t)New with {t.MyProperty1,t.MyProperty2}'。

因此,鉴于匿名类型构造用于指定键列,所以这不是指定外键名称的方法。

问题仍然存在:我们如何使用EF6.4中的Fluent API指定外键名称?

我正在尝试使用EF6.4上的Code First Migrations设置外键名称(而不是外键列)。我知道可以通过更新生成的迁移代码来进行设置,如下所示:.ForeignKey(“ ...

c# vb.net entity-framework-6 ef-migrations fluent
2个回答
2
投票

[不幸的是,在EF6中,没有内置的方法可以做到这一点。为了澄清您的问题,您要问的是如何指定基于模型中指定的外键创建的基础数据库约束的名称。对于迁移生成器而言,这将是一项工作。尽管EF6迁移中提供了传递约束名称的功能,但是如果您探索源代码,您会发现它实际上从未使用过,并且所有方法都是私有的和内部的。


0
投票

使用Fluent映射,ForeignKey样式将您的类中的属性名称作为参数。

© www.soinside.com 2019 - 2024. All rights reserved.