views:

43

answers:

1

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  A: 

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();
}
Lachlan Roche
The problem with that is that I'm using the repository pattern and I don't have direct access to the session object. I'm wrapping everything inside an IUnitOfWork instance which abstracts the session object + transaction and calling Commit() on the unit of work at the end which intern commits the NHibernate transaction.
Chris
I think I just need to add a Save method to my repository base classes. Apparently, despite me not having needed it until now, it's a pretty gaping hole in my framework.
Chris