NHibernate correct way to reattach cached entity to different session
Posted
by Chris Marisic
on Stack Overflow
See other posts from Stack Overflow
or by Chris Marisic
Published on 2010-05-28T21:42:15Z
Indexed on
2010/05/29
5:42 UTC
Read the original article
Hit count: 270
I'm using NHibernate to query a list of objects from my database. After I get the list of objects over them I iterate over the list of objects and apply a distance approximation algorithm to find the nearest object. I consider this function of getting the list of objects and apply the algorithm over them to be a heavy operation so I cache the object which I find from the algorithm in HttpRuntime.Cache
.
After this point whenever I'm given the supplied input again I can just directly pull the object from Cache instead of having to hit the database and traverse the list. My object is a complex object that has collections attached to it, inside the query where I return the full list of objects I don't bring back any of the sub collections eagerly so when I read my cached object I need lazy loading to work correctly to be able to display the object fully.
Originally I tried using this to re-associate my cached object back to a new session
_session.Lock(obj, LockMode.None);
However when accessing the page concurrently from another instance I get the error
Illegal attempt to associate a collection with two open sessions
I then tried something different with
_session.Merge(obj);
However watching the output of this in NHProf shows that it is deleting and re-associating my object's contained collections with my object, which is not what I want although it seems to work fine.
What is the correct way to do this? Neither of these seem to be right.
© Stack Overflow or respective owner