I'm trying to have a simple one to many relationship/hierarchy using NHibernate. I would like orphans to be deleted automatically but my current attempts to do so all result in an ObjectDeletedException. I'm wondering if someone can tell me what I'm doing incorrectly.
EDIT:
I should have specified that I'm loading a root Foo, then removing a child outside of the session, causing one or more children to be orphaned. The exception is occurring when I subsequently call SaveOrUpdate(root) in a second session. How can I rectify the difference in the list of children between the detached and modified object vs the object that is persisted in the database?
Sample code in question looks something like this:
Foo foo = new Foo();
Foo child1 = new Foo();
Foo child2 = new Foo();
foo.Children.Add(child1);
child1.Children.Add(child2);
// session #1
session.SaveOrUpdate(foo);
// so far, so good
// outside of any session
foo.Children.Clear();
// session #2
PutFoo(foo); // results in ObjectDeletedException
The object being persisted:
class Foo
{
private IList<Foo> children = new List<Foo> children;
public virtual int Id { get; private set; }
public IList<Foo> Children
{
get { return children; }
set { children = value; }
}
}
The FluentNHibernate mapping:
class FooMap : ClassMap<SyncDir>
{
public FooMap()
{
Id(x => x.Id);
base.HasMany(x => x.Children).Cascade.AllDeleteOrphan();
}
}
The method used to persist an object of type Foo:
void PutFoo(Foo foo)
{
using (var session = factory.OpenSession())
using (var transaction = factory.BeginTransaction())
{
session.SaveOrUpdate(foo);
transaction.Commit();
}
}