Tuesday, June 23, 2009

Guid.comb and synchronization

Synchronize an entity between two databases.

I had set up this records with a GUID and used the guid.comb from NHibernate to generate these for me.
Then I needed to synchronize this object with an other database.

Using NHibernate, just create a new session, evict the object from the first one, and save it the next one. No problem, except a new GUID was generated....

My assumption was that an entity with a guid.com generated GUID kept its value. I was wrong.

The answer lies in the ISession.Replicate. This allowes me to copy an entity from one session to another witout losing the generated key.
  foreach (var person in persons)
{
sourceSession.Evict(person);
targetSession.Replicate(person, ReplicationMode.Overwrite);
}
targetSession.Flush();

The ReplicationMode lets you choose the behaviour (Overwrite, LatestVersion, Ignore etc.)

No comments: