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.


Travis said...

How can I do this query in Nhibernate Linq:

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

Notice, I removed the wildcard.

Frank said...


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