Today's work encountered a strange problem, as follows:
"A different object with the same identifier value is already associated with the session:19519146"
The context of the exception is as follows:
1: Generated when a WCF remote call is net.tcp bound;
2: Calling a method through the UI does not produce the exception.
Analyze the problem:
As can be seen from the exception information, this problem is caused by an attempt to associate a new entity to the session (19519146) after Session.update has been updated on a set of entities, Because there are already entities of the same identifier under the session.
Also, refer to Session.update's instructions:
Update (Object entity)
Update the given persistent instance, associating it with the current Hibernate Session.
It is true that this problem is caused by the update (why it is not clear that the problem arises, and someone knows not to hesitate to let us know).
Solution:
Review the persistence methods provided by the session:
Object Merge (Object entity)
Copy the state of the given object onto the persistent object with the same identifier.
As can be seen in the definition of the merge interface, the interface is to copy the given entity to a persisted entity under the session (not knowing if the understanding is correct).
Therefore, you can avoid this exception by calling the merge () method.
Ps:
By looking up the data, the Session.evict () interface can purge persisted entities from the session's cache, and in the context of the problem, by first calling the method, clearing the original persisted entity, then update (), and no duplicate associating exception is generated.
The difference between session.update () and Session.merge () in NHibernate