Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: Adding an entity to a lazy loaded many-to-many relationship

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

like image 429
JontyMC Avatar asked Feb 18 '10 14:02

JontyMC


1 Answers

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.

like image 159
James L Avatar answered Sep 30 '22 21:09

James L