views:

183

answers:

3

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 transient entity. 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's 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:

a different object with the same identifier value was already associated with the session

The reason is because the store.Products collection already contains an entity with the same Id. How do I get around this problem?

A: 

Maybe You should call Database.SaveOrUpdate(store); instead of pure Save(store) ?

Luzik
Whoops, forgot to mention that `Database.Save()` does `NHibernate.ISession.SaveOrUpdate()` behind the scenes.
Daniel T.
SaveOrUpdate won't help in this situation, the error occurs because there is already an object in session.
jfneis
A: 

I'm not 100% positive in this case without more context, but a session merge might work.

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

Daniel Auger
+2  A: 

Instead of trying to merge the transient instance. Why not start with the actual instance...simply get the product by id, update the fields, and then Update().

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

or the merge way...

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