NHibernate 3.0 General Availability

Yesterday (4 Dec 2010) , NHibernate 3.0 was released.

This new version targets .NET 3.5, so the new API supports lambda expression now. For configuration, there are extension methods, that allowed us to ensure type safety.

Below is the example:

var nhConfig = new Configuration()
.Proxy(proxy =>
proxy.ProxyFactoryFactory<ProxyFactoryFactory>())
.DataBaseIntegration(db =>
{
db.Dialect<MsSql2008Dialect>();
db.ConnectionStringName = "MyConn";
db.BatchSize = 60;
})
.AddAssembly("MyProject.Model");
var sessionFactory = nhConfig.BuildSessionFactory();

Now NHibernate supports QueryOver method, which is new fluent syntax for criteria queries.

Previously we often use criteria query like this

var user=session.CreateCriteria<User>()
.Add(Restrictions.Eq("Email",emailToMatch))
.UniqueResult<User>();

The property is written in string, so if there is typo error, we won’t detect it during compile time. This problem is solved with QueryOver.

var user=session.QueryOver<User>()
.Where(u=>u.Email==emailToMatch)
.SingleOrDefault();

You may notice that the QueryOver syntax is similar to LINQ provider. However NHibernate has its own LINQ provider in the namespace NHibernate.Linq (which is integrated in the main assembly, NHibernate.dll).

var user= session.Query<User>()
    .Where(s => s.Email==emailToMatch)
    .FirstOrDefault();

var user=(from u in session.Query<User>()
    where u.Email==emailToMatch select u)
    .FirstOrDefault();

Note that I’m new to NHibernate, and I ‘m learning it from Jason Dentler’s NHibernate 3.0 cookbook, which is a good reference book. I bought the book along with ebook version from Packtpub website directly last month (somehow it is cheaper than Amazon) and the coupon is NHIBCBK20 . Until now I haven’t received the book (which is usual because the post here is slow and I don’t use express service) but I can download the ebook version directly from their website.