NHibernate Deleted object would be re-saved by cascade

后端 未结 2 943
再見小時候
再見小時候 2020-12-11 07:02

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 woul

2条回答
  •  青春惊慌失措
    2020-12-11 07:52

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

    public class Employee 
    {
        public virtual IList Occupations { get; set; }
    }
    public class Company
    {
        public virtual IList 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)

    
         // this above setting on Company side is making issues...
      
      
    
    

提交回复
热议问题