1

Having tried several solutions to get NHibernate to delete orphan records. Given the following structure:

public class Parent {

    public virtual ICollection<Domain> Domains {get;set;}

}
public class Domain{

    public virtual Parent Parent {get;set;}
}

UPDATE: It had nothing to do with the setter. This caused something else to go wrong which was fixed. But the deletion of orphans still does not happen I have tried the following:

  • Add an attribute on Domains (and on the Parent property of the Domain class) according to http://mookid.dk/oncode/archives/643

  • Added Automapping like:

    AutoMap.Override<Parent>(map => { map.HasMany(x => x.Domains).Inverse().Cascade.All(); })
    AutoMap.Override<Parent>(map => { map.HasMany(x => x.Domains).Cascade.All(); })
    

Both caused the Domain records to be stored with Parent_Id = null.

Is there any good example on how to achieve this in combination with Automapping?

amaters
  • 2,266
  • 2
  • 24
  • 44
  • i don't get it. What is that Domains.Remove and Domains.Add all about? SetName doesn't make any sense to me. And for the first automapping line: you will have to set the parent property in a newly created domain instance manually, as the domain instance controls the relationship. After that the domain instance should be persisted with the parent id. – Dirk Trilsbeek Mar 23 '12 at 09:57
  • It is just an example on Model manipulation. Whenever Parent.Name changes i need to Delete 1 Domain from the collection and Add a new one. The problem is not in the persistence because new domains are being persisted. It is just that Orphan Domain records don't get deleted but instead have their Parent_Id column set to null – amaters Mar 23 '12 at 10:09
  • could you post the code for the model manipulation? What you describe could possibly happen if you remove your domain instance from the Domains collection and at the same time manipulate/remove the Parent association in the Domain instance. Maybe NHibernate has a hard time tracking the orphaned instance. – Dirk Trilsbeek Mar 24 '12 at 10:43
  • update: i have removed the SetName from the setter and made it public. It seemed it had to do with the onflush and onpersist event which triggered a lot of set actions. I no longer get an error, but the cascadedelete of Orphans still does not happen. – amaters Mar 26 '12 at 14:13

1 Answers1

3

you do not have specified deleteOrphan

map.HasMany(x => x.Domains).Inverse().Cascade.AllDeleteOrphan()
Firo
  • 30,626
  • 4
  • 55
  • 94
  • Thanks for the help but still the same result. I still get records with null as parent_id – amaters Mar 29 '12 at 12:30
  • Seems this did work: `map.HasMany(x => x.Domains).Cascade.AllDeleteOrphan()` After all I was almost there :) – amaters Mar 29 '12 at 12:42