3
votes

I have the following mapping in nhibernate. When I call Session.Merge(myparent) I get the an error on the insert indicating that NULL cannot be inserted into the foreign key (ParentItemId) column.

How can I adjust the mapping so that the parent key is inserted on insert. If I make the foreign key nullable this mapping works, but two separate statements are issued to the database.

This relationship is a one to many without a reference back to the parent on the child class.

  • The child class has no parent property.
  • The child is dependent on the parent.
    HasMany(map => map.Children).Table("ChilrenTable")
       .KeyColumn("ParentItemId") // this is not nullable.
       .Cascade
       .AllDeleteOrphan();
    

    example update

    // entity here is the parent instance, which contains the list
    // of children.
    using (var tx = Session.BeginTransaction())
    {
        entity = Session.Merge(entity); // this line causes the problem.
        Session.SaveOrUpdate(entity);
        Session.Flush();
        tx.Commit();
        return entity;
    }
    
  • 1

    1 Answers

    3
    votes

    Inverse Attribute in NHibernate

    HasMany(map => map.Children).Table("ChilrenTable")
       .KeyColumn("ParentId") // this is not nullable.
       .Inverse()  // <--- This is the key here
       .Cascade
       .AllDeleteOrphan();