2

I have an intermittent problem in a production system that I haven't been able to recreate locally. What appears to be happening is that for no obvious reason during an edit of a child entity and saving the parent containing the collection the parent association on the child entity is removed in the database. Effectively orphaning the child entity.

Here is the fluent mapping:

 mapping.HasMany<ExpenseItem>(x => x.ExpenseItems).Cascade.AllDeleteOrphan();

The entity can also be directly saved (it is also aggregate root), but during testing this has not be shown to remove the parent association.

There are no references to the parent itself in the child object the association is all in the DB handled by Nhibernate.

There is also no possibility of assigning the same child entity to another parent as expense item (child entity) cannot be added outside of its parent directly. See code below.

 public virtual ExpenseItem AddNewExpenseItem(ExpenseAnalysis analysis,
            string recipientName,
            string purchaseAccountReference,
            string expenseDescription,
            string expenseNotes,
            Money value,
            VATAnalysis vat)
        {
            Validate.IsNotNull<ExpenseAnalysis>(analysis);
            Validate.IsNotNull(expenseDescription);
....


            ExpenseItem newExpenseItem = new ExpenseItem(analysis,
                recipientName,
                purchaseAccountReference,
                expenseDescription,
                expenseNotes,
                value,
                vat,
                expenseItemUniqueReference,
                true,
                Candidate.Assessment);
            _expenseItems.Add(newExpenseItem);
....

Any ideas?

markb
  • 79
  • 1
  • 7
  • Could you add your model please, specificly where you declare/initialise the expenseitems – Nexus Jul 09 '12 at 11:10

2 Answers2

1

It would definitely help to see your mapping but take a look at

I'd also map the ExpenseItem with a reference to its parent

How to delete child object in NHibernate?

basically you ve to set inverse on the relationship so that NHibernate does not try to update the deleted record with a null victim. And you set Cascade.All | Cascade.DeleteOrphans so that we aren't just breaking the relationship by nulling out the victim, but deleting the entire child record.

Community
  • 1
  • 1
Fran
  • 6,440
  • 1
  • 23
  • 35
0

This problem was caused by a bug in NHibernate. I had set the session to flush never however when you call isdirty on the session the session was being flushed first. The user was deleting the expense item then cancelling the edit but during the isdirty check the deletion was being flushed. Managed to work around this by changing how the session was being managed for this type of dialog.

markb
  • 79
  • 1
  • 7