Is there an alternative to ISession.Merge() that doesn't throw when using optimistic locking?

余生长醉 提交于 2019-12-24 11:29:23

问题


I've been trying to use ISession.Merge() to keep coherence between two sessions, but it fails when the merged instance has a higher Version property than the one loaded in the session (with a StaleObjectStateException).

Is there an alternative method that would work when the Version fields do not match ?


回答1:


Try calling:

Session.Lock(string entityName, object obj, LockMode lockMode);

with LockMode.Force. The remarks for that method state:

This may be used to perform a version check (NHibernate.LockMode.Read), to upgrade to a pessimistic lock (NHibernate.LockMode.Upgrade), or to simply reassociate a transient instance with a session (NHibernate.LockMode.None). This operation cascades to associated instances if the association is mapped with cascade="lock".

And for LockMode.Force:

Similar to NHibernate.LockMode.Upgrade except that, for versioned entities, it results in a forced version increment.




回答2:


There doesn't seem to be any way to safely merge entities between sessions, at least with optimistic-locking.

I'm going with another pattern: each session has its own copies of each entity, and I refresh() the instances on each session as needed. This has added overhead in memory usage and round-trips to the DB, but it seems to work.



来源:https://stackoverflow.com/questions/6845815/is-there-an-alternative-to-isession-merge-that-doesnt-throw-when-using-optimi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!