NHibernate Cascade=save-update"?

John picture John · Jul 20, 2009 · Viewed 12k times · Source

Disclaimer: I am an NHibernate noobie so hopefully this question makes sense. I have a many-to-many relationship between two classes something like…

public class Entity1
{
    public virtual Guid EntityId { get; set; }
    public virtual IList<Entity2> Entity2List;
} 

Public class Entity2
{
    public virtual Guid EntityId { get; set; }
    public virtual IList<Entity1> Entity1List;
}

I’ve added a many-to-many relationship with a bag in both class mappings, defining an association table but am unsure of which cascade option to use. I want to be able to create a new Entity1 instance, add a new Entity2 instance to it’s list, call Save, and both be inserted into the database (and vice-versa). When deleting an entity it should delete any associations to child entities but not the child entity itself. Should I be using cascade="save-update"?

Answer

g . picture g . · Jul 20, 2009

Yes. It sounds like 'save-update' is what you want, in this case.

I never found a great explanation of each cascade option in the documentation, but have used this blog post by Ayende as reference.

  • none - do not do any cascades, let the users handles them by themselves.
  • save-update - when the object is saved/updated, check the associations and save/update any object that require it (including save/update the associations in many-to-many scenario).
  • delete - when the object is deleted, delete all the objects in the association.
  • delete-orphan - when the object is deleted, delete all the objects in the association. In addition to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.
  • all - when an object is save/update/delete, check the associations and save/update/delete all the objects found.
  • all-delete-orphan - when an object is save/update/delete, check the associations and save/update/delete all the objects found. In additional to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.