C# – Fluent NHibernate cascade delete problem

cfluent-nhibernatenhibernate

I'm having a problem with fluent nhibernate cascade delete. I'm sure I'm doing something wrong because it isn't working.

Here are my objects:

public class Parent
{
    public int Id { get; set; }
    public IList<SequencedChild> SequencedChildren { get; set; }
}

public class SequencedChild 
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public int ChildId { get; set; }
    public int Sequence { get; set; }
}

public class Child 
{
    public int Id { get; set; }
}

And here is my mapping:

HasMany(m => m.SequencedChildren).Inverse().Cascade.Delete();

So I have a parent with some sequenced children and I want to update that parent to have no children. When I do an update with no sequenced children on that parent I expect that in my SequencedChild table the records that have the id of the parent will be deleted. But for some reason NHibernate is trying to update the ParentId of those records with null – which fails as ParentId is not null. EDIT: I'm also expecting that the Child object is unaffected (which is behaving correctly).

I had a look at a few questions and they all suggest the use of inverse but I am already doing this. What am I doing wrong?

Best Answer

So I managed to find a solution which turned out to have multiple steps:

  1. As James pointed out in a comment ParentId/ChildId should be Parent/Child references not just the ids (+1 for that)
  2. SequencedChild needs to have an explicit map that sets cascade to none
  3. When doing the update, don't overwrite the SequencedChild list. First clear it then add the new items. (Or just clear if you arent replacing the items)
  4. The Inverse() call is not necessary
  5. The ParentId field in the db table should be nullable because nHibernate insists on updating it to null before it deletes it. (if anyone knows a way around this leave a comment)
Related Topic