0

我有两个实体,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"))
4

1 回答 1

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"))
于 2013-06-28T15:17:10.343 回答