views:

128

answers:

1

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.

A: 

Lock should work. I think your problem is that the original session is not disposed yet. Try disposing the original session after you cache the object.

Jan Willem B