Search code examples
nhibernateormstateless-session

Update Child ForeignKey using Nhibernate Stateless Session


I understand that while using the stateless session one must explicitly save an object association (child)

If I have the following objects:

public class Parent()
{
    public int Id {get;set;}
    public string Name {get;set;}
    public IList<Child> Childs {get;set;}
}

public class Child()
{
    public int Id {get;set;}
    public string Name {get;set;}
}

I modify an instance of parent and add one child to it, I then save the parent and child using the following statements:

statelesssession.Update(parentInstance);
statelesssession.Insert(parentInstance.Childs.Last());

Doing this updates sucessfully the parent and creates the child record, however the field Parent_Id from the Child Table stays null, therefore there the association is not recorded.

How can I manually record the association using the stateless session?


Solution

  • I don't see a many-to-one property on Child that points back to Parent. That's what NHibernate would use for saving the Parent_id column. You need:

    public class Child
    {
        public int Id {get;set;}
        public Parent Parent {get;set;} // this is missing
        public string Name {get;set;}
    }
    

    ... and the corresponding NHibernate mapping. Also, make sure that you set the value of child.Parent when you add the child to the parent.

    Another thing, given the sequence of events you describe ("I create an instance of parent and add one child to it") I would have expected to see an Insert for the parent instead of an Update.