代码之家  ›  专栏  ›  技术社区  ›  kamranicus

当在M:N关系上设置all delete orphan时,NHibernate没有检测到其他关联的问题

  •  0
  • kamranicus  · 技术社区  · 16 年前

    以下是场景:

    一个人可以有许多电子游戏

    一个电子游戏可以属于许多人

    商店和电子游戏之间的M:N关系也是一样的

    在DB中,除了这些实体之外,只有两个简单的连接表PersonVideoGames和StoresVideoGames。

    业务规则:

    • 我 想在电子游戏桌上放个电子游戏吗 如果它与任何事物无关
    • 我 如果它与 至少一个其他对象
    • 您不直接管理视频游戏,而是由其他方(商店、个人)管理保存/删除视频游戏。

    这可以使用NHibernate映射吗?从我的实际项目实施来看,它似乎不适用于基本的个人<->视频游戏级别。

    NHibernate目前将删除该视频游戏,即使它仍然与其他人有关联(它不是真正的孤儿)。

    人 有M:N的视频游戏作为一个集,与级联风格的所有删除孤儿启用。

    电子游戏

    此人的视频游戏财产没有公共设置器。它的功能如下:

    Public Overridable Sub SetVideoGames(ByVal games As IEnumerable(Of VideoGame))
        If Me.VideoGames Is Nothing Then Exit Sub
    
        ' Add if the game isn't in the old list.
        For Each g In games
            If Not Me.VideoGames.Any(Function(g2) g2.Id = g.Id) Then
                Me.VideoGames.Add(usr)
            End If
        Next
    
        ' Remove if the game isn't in the new list
        For Each g In Me.VideoGames.ToList()
            If Not games.Any(Function(g2) g2.Id = g.Id) Then
                Me.VideoGames.Remove(g)
            End If
        Next
    End Sub
    

    然后,每当我救人时,我都会得到一个视频游戏列表(现有的或全新的),然后使用设置方法:

    ' listOfVideogames is just a list of ShortTitle strings
    
    Dim result As New List(Of VideoGame)()
    Dim newGames As New List(Of VideoGame)()
    Dim existingGames As IList(Of VideoGame) ' = Session.Get(blah, gets the existing games for this person)
    
    ' Add the existing games to the result set
    result.AddRange(existingGames)
    
    ' Get any titles from the given list not in the existing list
    For Each title In listOfVideogames.Except(existingGames.Select(Function(g) g.ShortTitle))
        Dim newGame As New VideoGame() With {
            .ShortTitle = title 
        }
    
        newGames.Add(newGame)
    Next
    
    ' Add them to the resultset
    result.AddRange(newGames)
    
    existingPerson.SetVideoGames(result)
    ' Do other updates
    MyNHibernateDataProvider.Save(existingPerson)
    

    为了那个人 匹配它或创建具有该短标题的新域对象(假定只有Id和ShortTitle是唯一的属性)。

    有人知道怎么了吗?为什么NHibernate在从一个视频游戏集中删除一个视频游戏时没有检测到它已经与其他人关联了呢?

    此外,假设我能做到这一点,那么一旦我建立了更多的M:N关系(比如商店),这个场景还会有效吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Diego Mijelshon    16 年前

    all-delete-orphan 没有那么强大。如果有其他关系,则必须手动管理删除级联。