We have a entity with a many-to-many collection mapped as a lazy loaded bag. When we load up the entity, the collection is not loaded - great. Now we want to add a new entity to that collection. As soon as we do this, the collection is loaded up.
How do we add the new entity without loading up the whole collection (the collection is large)?
The reason for this behavior is that you are referencing your collection when you Add() an new item to it. This reference triggers the lazy-load.
I've found it best to avoid explicit many-to-many mappings in NHibernate. I normally use two one-to-many associations to a third entity, which works like a link table. Make sure you set the many sides of the relationship to inverse="true". You can then directly perform:
session.Save(new LinkEntity(leftSideInstanceOrProxy, rightSideInstanceOrProxy);
Another benefit is that there's normally information about the relationship that you want to save, which can also go in the new entity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With