Error in Cascade : deleted object would be re-saved by cascade
Asked Answered
T

1

9

I have a project by NHibernate implementation and using Lazy Loading. I have two class in this project : Person and Family. Relation between Those two is aggregation, is mean a Person has a list of Person. Maping is :

  <class name="Person" table="Person_Person" >

    <id name="Id" type="Int64" unsaved-value="0">
      <generator class="native" />
    </id>

    <bag name="Families" inverse="true" table="Person_Family" cascade="all-delete-orphan" >
      <key column="Person_id_fk"/>
      <one-to-many class="Domain.Entities.Family,Domain.Entities"/>
    </bag>

  </class>

In this project, I Get a person by ID then remove a family of families person.

Person person = SessionInstance.Get<Person>(id);
foreach (Family fam in person.Families)
    if (fam.Name == "Jaun")
        SessionInstance.Delete(fam);

The family not deleted, Because throw a exception by this message : deleted object would be re-saved by cascade (remove deleted object from associations)[Domain.Entities.Family#167]

How can i delete a family of person?

Tremann answered 31/10, 2011 at 13:48 Comment(0)
K
13

Basically what NHibernate is complaining about is that you are explicitly telling it to delete a record for the Family, then when you re-save the Person the Family will be put right back in place, because the Person still has a reference to it in its list of Families.

Instead, NHibernate is telling you to deal with this relationship in the object-oriented manner that NHibernate allows you to use. Simply remove the reference to the "Jaun" family from the Person.Families list, then persist the Person. When you do this, NHibernate will remove the relationship between that Family and that Person. If the Family is now no longer referenced by anything else, since you have set the Cascade property to "all-delete-orphan", the "Jaun" Family record will be deleted completely from the DB.

Khoury answered 31/10, 2011 at 14:28 Comment(1)
person.Families.Remove(fam); SessionInstance.Save(person);Foothold

© 2022 - 2024 — McMap. All rights reserved.