Search code examples
c#nhibernatefluent-nhibernate

Adding instance of Parent with one-to-one Child


I have a parent class, Parent, which has a one-to-one relationship with a child class, Child.

When I add a new Parent, I want to add a Child onto the parent at the same time.

Below are my classes:

public class Parent
{
    public virtual int Id { get; }
    public virtual Child Child { get; set; }
}

public class Child
{
    public virtual int Id { get; }
    public virtual Parent Parent { get; set; }
}

I am using NHibernate and the HasOne / one-to-one mappings outlined here: https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping

Below is the code from my Handle() method in my AddParentRequestHandler:

var parent= new Parent();

var child = new Child()
{
    Parent = parent;
};

parent.Child = child;

session.Save(parent);

When this is executed I get the following error: Cannot insert the value NULL into column 'ChildId', table 'dbo.Parent'; column does not allow nulls. INSERT fails.`

ChildId on Parent and ParentId on Child are both not nullable fields.

Is there any way of fixing this and still keep these fields not nullable? Thanks in advance.


Solution

  • I needed to do 2 things to solve this one.

    Firstly, I removed the ChildId column from the Parent table in the schema.

    Then, I moved the session.Save above the code where I assign the child:

    var parent= new Parent();
    
    session.Save(parent);
    
    parent.Child = new Child
    {
        Parent = parent;
    };
    

    So now I do not have any nullable Id fields and can persist a parent with a child.