NHibernate Many-to-Many removes all associations before inserting

I have a Users table and a Networks table with many relationships between them (a user can be long for several networks, and a network can contain many users). Many-to-many relationships are stored in the UserNetworks table, which has only two columns: UserId and NetworkId.

My classes are as follows:

public class User { public IList<Network> Networks {get; set;} } public class Network { public IList<Usre> Users {get; set;} } 

NHibernate mappings for these many-to-many collections look like this:

User.hbm.xml:

 <bag name="Networks" table="UserNetworks" cascade="save-update" inverse="true"> <key column="UserId" /> <many-to-many class="Network" column="NetworkId" /> </bag> 

Network.hbm.xml:

 <bag name="Users" table="UserNetworks" cascade="save-update"> <key column="NetworkId" /> <many-to-many class="User" column="UserId" /> </bag> 

In my code, I create a connection between the user and the network as follows:

 user.Networks.Add(network); network.Users.Add(user); 

I would expect the SQL run to just execute one INSERT in the UserNetworks table. Instead, it performs a DELETE on the UserNetworks table with NetworkID = X, then proceeds to reinstall all UserNetworks rows with the new association.

What am I doing wrong?

+4
source share
1 answer

Design Behavior. See, NH does not know what is current / new / deleted in the list. Thus, deleting everything and inserting everything in the list will make sense.

+5
source

All Articles