我正在尝试使用EF6.4上的Code First Migrations设置外键名称(而不是外键列)。
我知道可以通过更新生成的迁移代码来进行设置,例如:
.ForeignKey("Documents",Function(t) t.DocumentId,cascadeDelete:=True,name:="FK_Sections_Documents")
...但是我想使用Fluent API在添加迁移之前完成。
我似乎想起了关于HasForeignKey()
调用接受Func
的某些事情,该调用在其主体中包含对匿名类型的调用,例如我们发现的here。但是,如果我能找到任何讨论该类型的一般结构的东西,我会很惊讶。
官方文档未对此进行讨论:
也不做这些类似的问答以完全解决问题:
- EF Code First Fluent API specifying the Foreign Key property
- Entity Framework Code First Mapping Foreign Key Using Fluent API
- Specifying Foreign Key Entity Framework Code First,Fluent Api
这个问题是几个月前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
如何设置外键名称,或者(更具体的说,假设我没记错的话)该匿名类型的一般结构应该是什么?
-更新-
我尝试过:
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指定外键名称?