我有一个 POCO 代表用户填写的表格。表格上大约有 10 个不同的地址,所以我将它们分成一个单独的地址 POCO。问题是如何建立关系。
我希望能够做什么:
Public Class formtofillout
Public Property form_id As Integer
<ForeignKey("address_1")> _
Public Property address_1_id As Integer
<ForeignKey("address_2")> _
Public Property address_2_id As Integer
<ForeignKey("address_3")> _
Public Property address_3_id As Integer
<ForeignKey("address_4")> _
Public Property address_4_id As Integer
<ForeignKey("address_5")> _
Public Property address_5_id As Integer
<ForeignKey("address_6")> _
Public Property address_6_id As Integer
<ForeignKey("address_7")> _
Public Property address_7_id As Integer
<ForeignKey("address_8")> _
Public Property address_8_id As Integer
<ForeignKey("address_9")> _
Public Property address_9_id As Integer
<ForeignKey("address_10")> _
Public Property address_10_id As Integer
Public Overridable Property address_1 As address
Public Overridable Property address_2 As address
Public Overridable Property address_3 As address
Public Overridable Property address_4 As address
Public Overridable Property address_5 As address
Public Overridable Property address_6 As address
Public Overridable Property address_7 As address
Public Overridable Property address_8 As address
Public Overridable Property address_9 As address
Public Overridable Property address_10 As address
End Class
并且不确定在地址 POCO 上做什么来代表这种关系的另一端。但是...这给了我一系列错误:
这个:
Introducing FOREIGN KEY constraint 'FK_dbo.formtofillout_dbo.address_1_id' on table
'formtofillout' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION
or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
我认为还有其他一些人。
为了让它工作,我没有在“formtofillout”POCO 中创建特定的 id 列。相反,我只是创建了导航属性:
Public Class formtofillout
Public Property form_id As Integer
Public Overridable Property address_1 As address
Public Overridable Property address_2 As address
Public Overridable Property address_3 As address
Public Overridable Property address_4 As address
Public Overridable Property address_5 As address
Public Overridable Property address_6 As address
Public Overridable Property address_7 As address
Public Overridable Property address_8 As address
Public Overridable Property address_9 As address
Public Overridable Property address_10 As address
End Class
然后在 OnModelBuilding 事件中,我为每个地址添加了以下内容:
modelBuilder.Entity(Of formtofillout).HasOptional(Function(n) n.address_1).WithRequired().WillCascadeOnDelete(False)
modelBuilder.Entity(Of formtofillout).HasOptional(Of address)(Function(n) n.address_1).WithMany().Map(Function(m) m.MapKey("address_1_id"))
这行得通,当我执行迁移时,使用 address_1_id、address_2_id 列等创建了表。但是这些 ID 列在数据库中,但不在 POCO 中。如何设置它以获取 POCO 和表中的外键列?