Posts tagged ‘NHLambdaExtensions’

The New World of NHibernate

NHibernate has always been a great tool for data access but there are a couple things that have always bugged me; the mapping files and the non-type-safe querying. There are now some great tools out there that solve these problems.

Mapping files has always been a pain for me. It’s not the most intuitive thing and it’s really easy to miss-type something in the xml hbm files. I have started using Fluent Nhibernate to do my mapping files, which has made my life with NH a lot better. Not only do I no longer have to edit xml files, but now the mappings are type-safe. Fluent Nhibernate is a tool that I don’t think I could live without now.

POCO:

public class MyClass
{
    public virtual int? Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual MyReference MyReference { get; set; }
    public virtual IList<MyReference> MyReferenceCollection { get; private set; }
}

Mapping:

public class MyClassMap : ClassMap<MyClass>
{
    public MyClassMap()
    {
        Id( m => m.Id );
        Map( m => m.Name );
        References( m => m.MyReference );
        HasMany( m => m.MyReferenceCollection );
    }
}

The other annoying thing is creating queries that aren’t type-safe, which makes doing re-factors a pain. You would think when using the Criteria language instead of HQL that it would be type-safe, but you still are using strings for the column names. I recently found a tool called NHLambdaExtensions which makes doing Criteria queries type-safe. This makes me sleep a little better at night.

// This:
session.CreateCriteria( typeof( MyClass ) ).Add( Expression.Eq( "Name", name ) );

// Becomes this:
session.CreateCriteria( typeof( MyClass ) ).Add<MyClass>( m => m.Name == name ).List();

What about the Linq-To-Everything craze? I’m definitely a person that loves Linq and use it constantly, so naturally I’m wondering when a Linq-To-NHibernate provider will be coming out. Oren Eini had a simple implementation going but didn’t handle many of the complex scenarios (or so I’ve read, and I must say, he’s a coding machine). But don’t fear, Steve Strong has been employed to create a fully functional Linq-To-NHibernate provider. I’m excited to see it come to fruition and can’t wait to actually use it. You can keep up with the progress at Steve’s blog at http://blogs.imeta.co.uk/sstrong.