NHibernate – object with same identifier value was already associated

One of the awesome capabilities of NHibernate is its 1st and 2nd level caching functionality. Each time a query is submitted for execution NHibernate first looks in the cache for the entity before taking the query to the database and selecting the data.

There is a lot of terminology you need to know before you can master this concept. We will start with the difference between a transient and a persistent object.

A transient object simple means the instance of a class which has been created within a given context and will cease to exist once that context no longer exists. A persistent object was once a transient object but at some point changed to be persisted, in NHibernate terms a persisted object exists on the database or at some point will exist on the database.

The following error occurs when you attempt to persist a transient entity which is already persisted. NHibernate guarantees that a 1 to 1 mapping of persisted objects and database rows. So when you attempt to add a 2nd object with the same identifier, this error is thrown.

image

To resolve this issue you can use the NHibernate Merge() method. This method merges a persisted entity with a detached or transient entity.