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.)

Thursday, June 18, 2009

Linq To NHibernate

Compile your queries

One of the hardest things to do with a database application (e.g. a c# WinForm) is to create all the queries in your app. Where to put them in the model? Use queries, or make stored procedures on the database etc etc.
Then creating all these queries in your code as strings;
"SELECT name, age, .. FROM ..."

This is a lot of work and causes runtime errors because these queries aren't checked at compile-time. Then there are issues of caching, relational data, locking etc etc. All these issues can be solved by NHibernate. This framework maps your OO-Model to your relational model and creates the queries, relations, locking etc for you.
But still there are these runtime errors which may occur, because even a Criteria/Expression in NHibernate uses strings as properties.

.Add(Expression.Like("Title", "Linq To%"))

This can be solved using Linq To NHibernate. This extension to the ISession creates an IQueriable which uses the intellisense of Visual Studio

var q = from tasks in session.Linq<task>()
where tasks.Title.StartsWith("Linq To")
select tasks;

Linq To NHibernate also eases creating queries with multiple joins:

var q = from tasks in session.Linq<task>()
where tasks.Owner.Address.City == "Dalem"
select tasks;


I find Linq To NHibernate a great help with developing my database applications.