tags:

views:

67

answers:

2

We are trying to use NHibernate 1.1 to as the persistence layer behind a web service API. Nothing new there. We use Automapper to translate the domain objects we get from (Fluent-)NHibernate to DTO's which we send over the wire.

The problem we are seeing is the following scenario:

  1. We read an object from the repository
  2. We translate that object (via Automapper) into the DTO form.
  3. After some, perhaps trivial fiddling, the object is mapped back from DTO to the Fluent-Nhibernate object (including the primary key which cannot change).
  4. We save the object.

After step 4 we get a Nonuniqueobjectexception from NHibernate and it creates a new row to save the object (with a new primary key). We want to update the original row but instead, new rows get modified(!)

So, in this situation, how can we convince NHibernate to do an actual update instead of an insert operation?

BTW, if we skip the translation to the DTO and back, there is no problem with the update.

== Tevya ==

A: 

1) NHibernate 1.1 or Fluent NHib 1.1?
2) I think you have a session management problem. If you load one object in session1 and try to persist it without attaching the actual object to session2 you will end up with a new row in the DB. Try to read and update the object within one session and see the results.

mynkow
Tevya
Well, I am just trying to find the core problem. If you still have problems event when the object is read and updated within one session then my suggestion is wrong. Just create a custom scenario and find what is the actual problem. Are you working on winforms or web application?
mynkow
A: 

You could try merging the object into your session.

// Assuming you already have a session open
// and you've already mapped your DTO back
using (var tx = session.BeginTransaction())
{
    var nhibernateObject = (YourNhibernateObjectType)session.Merge(mappedBackFromDTO);

    tx.Commit();
}
Daniel Auger