0
我有兩個實體,Search
和SearchTerm
,具有多對多的關係。當我創建一個新的Search
並添加一個List(Of SearchTerm)
以及它時,一切正常。如果我嘗試使用已經存在的SearchTerm
,它與崩潰:在多對多中添加相關實體(EF 4.1)
同時節省不爲他們的關係暴露的外鍵的屬性的實體時出錯。 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"))