问题
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