6

I have this one-to-many association I created zilions of times with 'old' nhibernate or fluent. But I cann't make it work with mapping-by-code

These are the classes

 public class Parent
 {
      public virtual IList<Child> Children { get; set; }
 }

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

Nothing odd

and these are mappings classes

For Parent:

 Bag(x => x.Parent, m => m.Key(k => k.Column("Parent_id")));

Child:

 ManyToOne(x => x.Children, map => { map.Column("Parent_id"); map.Cascade(Cascade.All); });

If I do the following

 var parent = new Parent();
 parent.Children.Add(new Child());

 session.SaveOrUpdate(parent); 

I got correct INSERT for parent, but it does an UPDATE for any child added

UPDATE TableChildren
......
WHERE Id = 0 <-????

What's am I missing? I'm banging my head!!

Stefano.net
  • 1,078
  • 1
  • 11
  • 25

1 Answers1

11

I see two issues. The mapping seems to be inverted (Bag should go for Children, ManyToOne for a Parent). The essential setting here is also the inverse="true".

As in detail documented here:

The Children should be mapped like this:

Bag(x => x.Children, map => {
    map.Inverse(true);
    map.Cascade(Cascade.All);
    map.Key(k => k.Column("Parent_id"));
});

And the Parent like this

ManyToOne(x => x.Parent, map => 
{ 
    map.Column("Parent_id"); 
});

The inverse="true" is a way how to instruct NHibernate, that each child can manage itself. So, once the child is added into the Children collection, we also have to set its Parent! NHibernate will then INSERT the child with the correct reference in one step.

mxmissile
  • 11,464
  • 3
  • 53
  • 79
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Thank you. For the first it was a typo, I'm going to update the question. For the latter, you were right, but I wander I never used inverse this way before (and I use NHibernate since several years). I thought I had to use if I want to tell NH I manually manage children objects. I wander how old programs manage to work, indeed :D. I'm going to investigate. – Stefano.net Feb 13 '14 at 09:35
  • 2
    Enjoy NHibernate, amazing tool really ;) – Radim Köhler Feb 13 '14 at 09:45
  • 1
    Yes it is! No comparison with other ORMs ;) – Stefano.net Feb 13 '14 at 10:18