NHibernate Cascade Removing Children While Cleaning Collection

I searched so many places and still can not find the answer I'm looking for.

I am using NHibernate 3.2 - Display by code

I have the following mapping files:

public class ParentMapping: EntityMapping<Parent> { public ParentMapping() { Set(x => x.Children, map => { map.Cascade(Cascade.All); map.Inverse(true); }, r => r.OneToMany()); } } public class ChildMapping: JoinedSubclassMapping<Child> // This is a subclass of something else. { public RequiredSkillMapping() { ManyToOne(x => x.Parent, map => { map.NotNullable(true); }); } } 

Cascading save works fine.

 session.Save(parent) will save the children and associate them correctly. 

When I try to call:

 var parent = session.Get<Parent>(1); parent.Children.Clear(); session.Save(parent); or session.SaveOrUpdate(parent) or session.Update(parent) 

Objects remain associated with the parent.

It was working for me by calling:

 foreach(var child in parent.Children) { session.Delete(child); } parent.Children.Clear(); 

I was hoping there was a way to just keep the parent?

Greetings

James

+4
source share
1 answer

Cascade means that parent operations are cascaded for a child.

  • When you insert a parent, children are also inserted.
  • When a parent is removed, the children are also deleted.
  • The update is special in NH, but it also means that when the update is called with the parent, the children are also β€œupdated”.
  • etc.

The collection itself belongs to the parent, so changes to the collection are stored with the parent. But there is no reason to remove children when they are no longer in the collection. NH can't know if you need them for anything else.

There is a cascade-removal-orphans.

 map.Cascade(Cascade.All | Cascade.DeleteOrphans) 

This means that items that were in the collection and removed from the collection are deleted. This may be useful in your case. Please note that it is not possible to use elements for anything after removal from the collection. You cannot even add them to another parent.

To make NH remove unused items automatically correctly, in each case a permanent garbage collection will be required. It is extremely inefficient and not implemented by NH.

"remove foreach child" is ok. This is what you might have to do to tell NH when children are no longer in use and need removal.

+11
source

All Articles