2
votes

I'm working on a project with NHibernate that classes similar to the following:

public class Parent {
    public IList Children {get;set;}
    // ...
}

public class Child {
    // ...
}

I've got the Children property set to cascade all / delete orphan. Since I'm using the aggregate pattern and instances of Child class will only ever be referenced in the context of a Parent, I don't have a ChildRepository to delete the children directly - only a ParentRepository. However, when I retrieve the Parent object and call Parent.Children.Clear(), the children from the database are never deleted. How can I achieve this?

1

1 Answers

3
votes

Deleting child entities is this easy - just remove them from the collection and then save the parent entity. The collection should be mapped with all-delete-orphans.

parent.Children.Clear();
session.Save( parent );

// or 
parent.Children.RemoveAt(0);
session.Save( parent );

You can do this without Save() calls as well, unless your FlushMode is Never.

session.BeginTransaction();
parent.Children.Clear();
session.Transaction.Commit();

Using @Chris's UnitOfWork abstractionm this could look like:

using (var uow = new UnitOfWork()) {
    parent.Children.Clear();
}