Patrick
Patrick

Reputation: 2790

Nhibernate many-to-many add on both sides

I'm creating a many-to-many implementation with Nhibernate. Currently I have the below classes. In both classes I implemented the AddObjX(Objx obj) method to add the item to the collection.

Obj1
{
  int id;
  Ilist<Obj2> obj2;
}

Obj2
{
  int id;
  Ilist<Obj1> obj1;
}

In the mappings I have

HasManyToMany(x => x.Obj1)
   .Table("Obj1Obj2")
   .ParentKeyColumn("Obj1Id")
   .ChildKeyColumn("Obj2Id")
   .Inverse()
   .Cascade
   .SaveUpdate();

HasManyToMany(x => x.Obj2)
   .Table("Obj1Obj2")
   .ParentKeyColumn("Obj2Id")
   .ChildKeyColumn("Obj1Id")
   .Inverse()
   .Cascade
   .SaveUpdate();

When I now say

obj1.AddObj2(obj2);
Session.SaveOrUpdate(obj1);

I only get an association between obj1 -> obj2. So if I retrieve obj2 there is no obj1 coupled to it. When I retrieve obj1 there is an obj2 coupled to it.

When I do

obj1.AddObj2(obj2);
obj2.AddObj1(obj1);
Session.SaveOrUpdate(obj1);

I have the object in both scenario's. Is this as designed or am I missing something?

Upvotes: 1

Views: 295

Answers (1)

Rippo
Rippo

Reputation: 22424

Have you tried dropping the Inverse from the second HasManyToMany?

AFAIK you should only have one inverse as this instructs NH which side of mapping is responsible for insert.

See this post by northerdev also this follow up post .

Upvotes: 3

Related Questions