views:

1497

answers:

4

I'm getting a

"Found shared references to a collection" exception when saving an object.

Does anyone know what this means?

A: 

Do you have a reference to any of the objects in the collection somewhere else? Another session, possibly, or even within the same session in another object? Make sure that when you access hibernate, you are controlling the ONLY reference to those objects within any hibernate session.

Elie
+3  A: 

quick google says

  rel   Group n --- 1 User
         m             ^
         |             | inh
         |  rel        |
         --------- n Member

rel stands for relation (association) inh stands for inheritance

The exception is thrown after Member objects have successfully been created and then have been read from the database. After the last Member object was read the transaction is committed but this fails.

what do your mappings look like?

Scott Cowan
+3  A: 

In theory it means that you have 2 records which contain the same reference to another object. At the database level this is most likely a weak entity, however at the code level this is likely to be represented as a collection.

Have you copied another records collection? E.g.

Blog blog1 =  Blog.Find(1);
Blog blog2 = new Blog();
blog2.Entries =  blog1.Entries;
blog2.Save();

This code is for ActiveRecords, but as it is built on top of nHibernate the underlying principles are the same.

The interesting thing when i came across this issue was that the collection it referred to was incorrect. It was a different one.

If this is your issue try iterating through each item and assigning it to the new collection in stead. E.g.

Blog blog1 =  Blog.Find(1);
Blog blog2 = new Blog();

foreach (BlogEntry entry in blog1.Entries)
   blog2.Entries.Add(entry);
blog2.Save();
codemonkeh
+1  A: 

Thanks a ton (@Xian). I'm a newbie to NHibernate. Your solution save me a lot of time