6

In my solution I have a branch of business objects with associations. So when I try save a root object after processing I get an exception with message "Deleted object would be re-saved by cascade". What means that after deleting of an object its still exists in collections, other association and so on. Does somebody knows how to get a list of references to the deleted object. Its very difficult to find references without debugger support.

Gattaka
  • 147
  • 1
  • 9

2 Answers2

10

The most common scenario (my experience) is having two root objects having collections of some pairing/middle object.

public class Employee 
{
    public virtual IList<Occupation> Occupations { get; set; }
}
public class Company
{
    public virtual IList<Occupation> Occupations { get; set; }
}

Now, we have the Occupation like this

public class Occupation
{
    public virtual Employee Employee { get; set; }
    public virtual Company  Company  { get; set; }
}

So, what could happen:

  1. we remove an Occupation from employee.Occupations collection.
  2. During that transaction, unit of work, we also tuch and therefore load the Company
  3. Company gets initiated. Its collection of Occupations get loaded. So the reference to removed Occupation is kept there
  4. NHibernate says: Deleted object would be re-saved by cascade

Solution(s):

  • be sure that the Company is never loaded (stays as proxy)
  • or Remove() the Occupation also from company.Occupations
  • do not use mapping like this on Company side:

(do not use the cascade)

<bag name="Occupations" lazy="true" inverse="true" batch-size="25" 
     cascade="all-delete-orphan">
     // this above setting on Company side is making issues...
  <key column="Company_ID" />
  <one-to-many class="Occupation" />
</bag>
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Yes, but what if I have a lot of object types and a lot of logic. And now I can't find which busness object holds the reference(Employee? or Company? or Ocupation? in my case its additionaly Address, Country etc) Because NHibernate exception doesn't contains usefull information. Is there any way to find out the source under debuger? – Gattaka Dec 24 '14 at 18:30
  • 2
    @Gattaka The root of your problem is you are mixing Persistence Model and Domain Model. Doing so impose NHibernate problems upon your business objects, such as this problem. You cannot freely change your persistence models (i.e. NHibernate mapped models) because the system passes it everywhere. Radim answer is correct, but this problem is quite difficult to debug, as it often only arises with certain data pattern. – Doan Van Tuan Dec 25 '14 at 03:01
1

The above solutions didn't work for me. The instance I tried to delete was nowhere referenced in my code.

However, it was in NHhibernate. After clearing the session, it worked for me.

Displee
  • 670
  • 8
  • 20