我有两个实体,Search
并且SearchTerm
具有多对多的关系。当我创建一个新的Search
并添加一个List(Of SearchTerm)
时,一切正常。如果我尝试使用已经存在的SearchTerm
,它会崩溃:
保存不为其关系公开外键属性的实体时发生错误。EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。有关详细信息,请参阅 InnerException。
内部异常:INSERT 语句与 FOREIGN KEY 约束“FK_tblSearchesSearchTerms_tblSearchTerms”冲突。冲突发生在数据库“CASSAudits”、表“dbo.tblSearchTerms”、列“SearchTermID”中。该语句已终止。
这是示例代码:
Dim foundTerm As SearchTerm = DataSource.SearchTerms.FirstOrDefault(Function(term) term.FieldName = "fieldName")
DataSource.Searches.Add(New Search() With {
.Terms = New List(Of SearchTerm) From { foundTerm }
}
DataSource.SaveChanges()
这里是实体
Public Class SearchTerm
Public Property SearchTermID As Integer
Public Overridable Property Searches As ICollection(Of Search)
Public Property FieldName As String
Public Property ComparisonType As String
Public Property Value As String
End Class
Public Class Search
Public Property SearchID As Integer
Public Overridable Property Terms As ICollection(Of SearchTerm)
Public Property FromPage As String
Public Property SearchDate As Date
Public Property User As String
End Class
多对多关系是OnModelCreating
这样自定义映射的:
modelBuilder.Entity(Of Search) _
.HasMany(Function(search) search.Terms) _
.WithMany(Function(term) term.Searches) _
.Map(Function(m) m.MapLeftKey("SearchTermID").MapRightKey("SearchID").ToTable("tblSearchesSearchTerms"))