Core question: What is the preferred way to handle bidirectional many- to-many relationships where both sides require relationship management behaviour?
I think a good example would be a User <-> Group relationship, where ideally both sides need to own, or at least appear to own, the relationship. Meaning a user should be able to add itself to a group, and a group should be able to add a user to itself, and both should sides should be able to persist their own changes. The standard handling of many-to-many would have one side of the relationship handle the persistence. For this example let's say the Group owns the relationship with cascade="save-update" and the User is the inverse side. When I create a Group and add a User to it, then save the Group, all should work fine. However what if I also want to also be able to add a Group to a User and persist the changes from the User side? I would guess I could loop through the entire Group collection for the User and call save on each group object, but that seems messy. I have managed to build a different handling that seems to work, although not perfectly. In this case, both Group and User are set to cascade="none" and the handling is offloaded to the business logic. When adding a User to Group, or a Group to a User, the object being added must already be persisted and throws an exception if it is not. The relationship is then set manually ( User.Groups.Add(newGroup); newGroup.Users.Add(this); ) and persisted when either object is saved. You may be able to see the small problem here already. The relationship is persisted twice in this way: NHibernate: INSERT INTO core_UserToGroup (GroupId, UserId) VALUES (@p0, @p1); @p0 = '1', @p1 = '2' NHibernate: INSERT INTO core_UserToGroup (UserId, GroupId) VALUES (@p0, @p1); @p0 = '2', @p1 = '1' There is no primary key constraint on the created join table, so this is allowed and it actually does not cause any problems that I have found. The correct relationship is created/found/used/updated/deleted NHibernate without any exceptions or orphaned records(so far), but it's still somewhat messy. At this point I will refer back to the original question :) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "nhusers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/nhusers?hl=en -~----------~----~----~----~------~----~------~--~---
