【问题标题】:Add related entities in many-to-many (EF 4.1)在多对多(EF 4.1)中添加相关实体
【发布时间】:2013-06-28 23:17:10
【问题描述】:

我有两个实体,SearchSearchTerm 具有多对多关系。当我创建一个新的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"))

【问题讨论】:

    标签: entity-framework-4.1 many-to-many


    【解决方案1】:

    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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2011-07-30
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多