Problem with NHibernate does not detect other associations when all-delete-orphan is specified with respect to M: N

Here's the script:

I have 3 objects called Person, VideoGame and Store.

One person can have many VideoGames.

One VideoGame Can Own Many People

The same M: N ratio is between the Store and VideoGames.

In the database, the only thing besides these entities is two simple connection tables PersonVideoGames and StoresVideoGames.

Suppose everything has an Id property and they are unique.

Business Rules:

  • I don’t want the video to be in the VideoGames table if it is not connected with anything (orphan)
  • I do want it to be in the table if it is associated with at least one other object
  • You do not control VideoGames directly, and other parties (Store, Person) control the saving / deleting of video games.

Can this be done using NHibernate mapping? From my actual implementation of the project, it does not seem to work at the base level of Person ↔ VideoGame.

NHibernate will currently remove VideoGame, even if it is still connected to other people (this is not an orphan).

My mapping looks like this:

Person Has M: N from VideoGame as a set, with all-delete-orphan enabled with cascading style.

video game Has M: N rights as a set, with the update turned on with lazy-load preservation, reverse and cascading style.

Man does not have a public device for his VideoGames property. It has the following function:

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

, Person, ( ), set:

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

"ShortTitle". IEnumerable (Of String), "DA: O, BatmanAA, LBP2" .., , , ( , Id ShortTitle).

, - , ? NHibernate , VideoGame , VideoGame ?

, , , , M: N (, )?

0
1

all-delete-orphan . , .

+1

Source: https://habr.com/ru/post/1781881/


All Articles