0

I read this thread regarding my issue but still had questions.

I have two entities -- an Order and a Task. There is a one-to-many relationship between an Order and its child Tasks.

//Order.hbm.xml
<bag name="Tasks" table="Task" inverse="true" cascade="all-delete-orphan">
  <key column="OrderID" />
  <one-to-many class="Task, Orders" />
</bag>

//Task.hbm.xml
<many-to-one name="Order" column="OrderID" />

I would like to delete a Task and have NHibernate keep my Order in-sync.

My first attempt yielded the issue:

Deleted object would be re-saved by cascade

I resolved this by manually cleaning up Order's reference to Task before committing my transaction:

public void DeleteTask()
{
    NHibernateSessionManager.Instance.BeginTransaction();
    //Need to remove Order's reference to Task before deleting so that Task is not resaved.
    Task.Order.Tasks.Remove(Task);
    TaskDao.Delete(Task);
    NHibernateSessionManager.Instance.CommitTransaction();
}

It seems like this bit of code should be able to be handled by NHibernate's XML files, though. Is this a correct assumption? How would I need to change my NHibernate configurations such that when a Task is deleted the reference is automatically cleaned up for its parent Order, too?

Community
  • 1
  • 1
Sean Anderson
  • 27,963
  • 30
  • 126
  • 237

1 Answers1

3

Actually, since you have cascade="all-delete-orphan", you can do without the explicit Delete():

public void DeleteTask()
{
    NHibernateSessionManager.Instance.BeginTransaction();
    Task.Order.Tasks.Remove(Task);
    NHibernateSessionManager.Instance.CommitTransaction();
}

This is more DDD-ish, as you can do the changes from the model itelf without any references to NH, and then let NH's change tracking take care of the delete.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154