我有两个实体,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"))
答案 0 :(得分:0)
在Express Profiler的帮助下找到了问题。我向后映射了左右键,因此EF尝试将新搜索的SearchID
添加为关系的SearchTermID
。
modelBuilder.Entity(Of Search) _
.HasMany(Function(search) search.Terms) _
.WithMany(Function(term) term.Searches) _
.Map(Function(m) m.MapLeftKey("SearchID").MapRightKey("SearchTermID").ToTable("tblSearchesSearchTerms"))