Hello,
given a bidirectional association between to classes, say Parent and Child. You have to maintain both sides of the association:
Code:
Parent parent = new Parent();
Child child = new Child();
child.Parent = parent;
parent.AddChild(child);
Because this is error prone I tried to solved the problem by implementing the classes as follows:
Code:
class Parent {
   void AddChild(Child child) {
      if (!m_Children.Contains(child)) {
         m_Children.Add(child);
         child.Parent = this;
      }
   }
}
class Child {
   Parent Parent {
      get { return m_Parent; }
      set {
         if (m_Parent != null) {
            m_Parent = value;
            value.AddChild(this);
         }
      }
   }
}
To be able to load both classes with NHibernate I added the following collection to class Parent:
Code:
   IList Children {
      get { return m_Children; }
      set { m_Children = value; }
   }
But now I have a problem with lazy loading of the Children collection of class Parent. If the collection is lazy loaded and after that one of the Child objects is loaded, a call to the setter of Child.Parent tries to add the child to it's parents children collection, which is not loaded. A  LazyInitializationException is raised.
So my question is: how do you solve this problem? Is it indeed necessary to handle both sides of bidirectional associations "by hand" if using NHibernate?
Sincerely,
Stefan Lieser