Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

c# - NHibernate Deleted object would be re-saved by cascade

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...