简体   繁体   中英

fluent nhibernate mapping with not null foreign key (HasMany)

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; }
  • Inverse Attribute in NHibernate

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

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM