3

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;
    }
    
  • Jim
    • 14,952
    • 15
    • 80
    • 167

    1 Answers1

    3

    Inverse Attribute in NHibernate

    HasMany(map => map.Children).Table("ChilrenTable")
       .KeyColumn("ParentId") // this is not nullable.
       .Inverse()  // <--- This is the key here
       .Cascade
       .AllDeleteOrphan();
    
    Community
    • 1
    • 1
    Cole W
    • 15,123
    • 6
    • 51
    • 85
    • I tried this, but the merge is still failing. Perhaps it has something to do with the merge. I am merging changes back to the database from posted web data that is being sent to a WCF service. The WCF service is merging and updating the data. It still attempts to insert a null value, and then subsequently updates the foreign key value. – Jim Sep 13 '12 at 05:02
    • Reading a little further, it would seem that perhaps inverse only works with bi-directional relationships. In my case the relationship is not bi-directional. The parent owns the child items, but the child items have no parent property and hence no nhibernate mapping to the parent. – Jim Sep 13 '12 at 05:10
    • @Jim Maybe you should make it a bidirectional relationship. – Cole W Sep 13 '12 at 12:36
    • Hi Cole, that's what I am beginning to think as well. The reason I have not is that the serialization over WCF can be an issue with circular relationships. I think I will use bi directional relationships and mark all the data contracts as IsReference = true. – Jim Sep 13 '12 at 14:52