1

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 ?

Mathieu Garstecki
  • 1,589
  • 1
  • 13
  • 18

2 Answers2

0

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.

eulerfx
  • 36,769
  • 7
  • 61
  • 83
  • The documentation and litterature elsewere make me think that LockMode.Force will rather force a write of a new Version to the DB, rather than get the latest state...I'll see what I can do with it though. – Mathieu Garstecki Jul 29 '11 at 14:27
  • 1
    Confirmed, LockMode.Force forces NHibernate to send a SQL update, which is the opposite of what I want here. – Mathieu Garstecki Aug 02 '11 at 12:57
0

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.

Mathieu Garstecki
  • 1,589
  • 1
  • 13
  • 18