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:
- we remove an Occupation from
employee.Occupations
collection.
- During that transaction, unit of work, we also tuch and therefore load the
Company
- Company gets initiated. Its collection of Occupations get loaded. So the reference to removed Occupation is kept there
- 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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…