I want to delete an user which has many usergroups but those usergroups don't belong exclusivly to this user: other users can also be using this usergroups. And usergroups can exist even if no user references them.
I want to map the many-to-many relationship so that if a user is deleted, the relationship is automatically deleted but NOT the usergroup?
I tried Cascade.All as I thought cascades on many-to-many affect the relationship but not the other side. I thought that only Cascade.AllDeleteOrphan would do the otherside delete. Obviously I'm wrong.
It seems that I don't understand the cascade rules right. Can someone provide a clear explanation to me and maybe also a way to reach my goal?
Thanks
NHibernate
many-to-manyrelation does provide what we expect, let me explain it in more details. While we need only two entities User and Group, we will need Three tables:User,Group,UserGroup(with columns UserId, GroupId)C# entities:
hbm.xml our mapping will look like this:
This mapping with important setting
cascade="none"will do expected behaviour. This mapping says that there is a PairTableUserGroup, which does not have any entity representation. So, there cannot be any cascade setting effecting this table. This table is used hiddenly behind the scene.Pair table
When some user is deleted, then NHibernate will aslo remove all the relations from the
UserGrouptable (in fact this will be the first statement in the batch). This is just the relational reference constraint handling. We cannot leave anyUserIdin the tableUserGroups, which does not have its foreign key in theUsertable.The other relation end
Finally the cascade setting: Because the
UserGrouptable is managed without any our attention, the cascade is in this case applied to entityGroup- the other relation end. So setting it to all-delete-orphan could lead to complete deletion of all cross referenced records.Summary: cascade on a
bagwithmany-to-manyrelation is meant for the other end point, not the pairing table.