NHibernate Pitfalls: Adding to a Bag Causes Loading
Updated. Thanks Kenneth!
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
When adding an item to a one to many uninitialized lazy bag, all items are loaded. You would expect this to happen in a set, because NHibernate must check that the new item does not already exist in the database, but not on a bag.
The way to prevent this from happening is to specify lazy=”extra” in the mapping for the bag collection:
1: <bag cascade="all" inverse="true" lazy="extra" name="Details">
2: <key column="`ORDER_ID`" />
3: <one-to-many class="OrderDetail" />