0

I have Customer, CustomerGroups, Groups tables. Customer has 1:n with CustomerGroups and Groups has 1:n with CustomerGroups. In the create customer screen, user can choose the groups information of existing customer. So when I create a new customer, I am retrieving groups from existing customer and adding them

///
Customer cust = new Customer();
foreach(var item in getothercustomergroups())
cust.groups.add(item);
commit

This code is generating update statement and updating the customergroups table with newly added customerid, instead of inserting new records with new customerid. Due to this, all groups with prev. customer are gone. Could anyone please explain this behavior.

Sunny
  • 4,765
  • 5
  • 37
  • 72

1 Answers1

0

From your description, I would guess getcustomergroups has gotten customergroups from an existing customer via NHibernate. If so, NHibernate has associated each item in the foreach loop with the existing customer, so when you add item to a new customer, the new customer assumes ownership of that item.

You can avoid this by cloning the item. See How do I copy an object with NHibernate

Community
  • 1
  • 1
djw
  • 66
  • 3
  • Yes, seems to be the case. Now its working by doing this way. Customer cust = new Customer(); foreach(var item in getgroupsofexistingcustomer(id)) cust.groups.add(new group() {name="test",desc="test"} ); commit But I have question on same approach for other n:n relationship. I have a table associative table specified in the mapping and when I add the object directly i.e, without creating new object like order.items.add(item), it is getting inserted into associative entity without any issues. how is this possible? – Sunny Aug 29 '12 at 23:37