简体   繁体   English

NHibernate将缓存的实体重新附加到不同会话的正确方法

[英]NHibernate correct way to reattach cached entity to different session

I'm using NHibernate to query a list of objects from my database. 我正在使用NHibernate从数据库中查询对象列表。 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 . 我认为获取对象列表并将算法应用于对象的此功能是一项繁重的操作,因此我将在算法中找到的对象缓存在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. 在此之后,每当我再次获得提供的输入时,我都可以直接从Cache中拉出对象,而不必访问数据库并遍历列表。 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. 但是,在NHProf中观察此输出显示它正在删除并将对象包含的集合与对象重新关联,这并不是我想要的,尽管它似乎可以正常工作。

What is the correct way to do this? 正确的方法是什么? Neither of these seem to be right. 这些似乎都不对。

Lock should work. Lock应该起作用。 I think your problem is that the original session is not disposed yet. 我认为您的问题是原始会话尚未处理。 Try disposing the original session after you cache the object. 缓存对象后,请尝试处置原始会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM