How to save a transition object that already exists in an NHibernate session?

I have a Store that contains a list of Products :

 var store = new Store(); store.Products.Add(new Product{ Id = 1, Name = "Apples" }; store.Products.Add(new Product{ Id = 2, Name = "Oranges" }; Database.Save(store); 

Now I want to edit one of the Products , but with a transition object. This will be, for example, data from a web browser:

 // this is what I get from the web browser, this product should // edit the one that already in the database that has the same Id var product = new Product{ Id = 2, Name = "Mandarin Oranges" }; store.Products.Add(product); Database.Save(store); 

However, trying to do it this way gives me an error:

another object with the same identifier value was already associated with the session

The reason is that the store.Products collection already contains an object with the same identifier. How do I solve this problem?

+6
c # nhibernate persistence session-state castle-activerecord
source share
3 answers

Instead of trying to merge a temporary instance. Why not start with the actual instance ... just get the product by id, update the fields and commit.

 var product = session.Get<Product>(2); product.Name = "Mandarin Oranges"; tx.Commit(); 

or a way to merge ...

 var product = new Product{ Id = 2, Name = "Mandarin Oranges" }; var mergedProduct = (Product) session.Merge(product); tx.Commit(); 
+8
source share

I am not 100% positive in this case without any additional context, but merging sessions may work.

http://ayende.com/Blog/archive/2009/11/08/nhibernate-ndash-cross-session-operations.aspx

+3
source share

Perhaps you should call Database.SaveOrUpdate (store); instead of pure save (save)?

-one
source share

All Articles