Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 504
Ehsan Avatar asked Oct 31 '11 13:10

Ehsan


1 Answers

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.

like image 195
KeithS Avatar answered Oct 04 '22 14:10

KeithS