Tuesday, November 22, 2011

My NHibernate Configuration for Mono and PostgreSQL

I love C#. It is by far my favorite language. I have been using mono to write C# application on linux for a few years now.

Ruby is growing on me, but only because of Metasploit. I wouldn't even bother with Ruby if it weren't for MSF. Generally, I switch back and forth between C# and Ruby (and, coincidentally, Monodevelop and vim respectively) a few times a day, or even going at both at the same time.

One of my personal projects requires a lot of DB stuff. At a previous job, I was introduced to NHibernate, this is by far the easiest way to manage your DB objects within your code. While this job was Windows centric (MSSQL, visual studio, etc...), I have adapted what I learned to Linux as well. I like PostgreSQL more than I like MySQL, and am very happy that NHibernate supports this dialect. It wasn't straight forward, though, figuring out the exact details. Maybe this will help someone in the same boat I am in.

The most important thing is you hibernate.hbm.xml. This is where you SQL connection string is, and where you tell NHibernate what dialect of SQL you are using:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
        <property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
        <property name="connection.connection_string">
            Server=;Port=5432;Database=pgdb;User Id=postgres;Password=postgres;SSL=true;
        <property name="dialect">NHibernate.Dialect.PostgreSQL82Dialect</property>
  <property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>

This requires Npgsql.dll, which runs with Mono just fine. The small detail that caused me much stress early on was the dialect property name.

<property name="dialect">NHibernate.Dialect.PostgreSQL82Dialect</property>

At first, I was missing the "82" in the middle of the dialect name. This defaults to PostgreSQL 7.4. I am running 8.4, and there were incompatibilities that caused issues. After a day or two, I finally figured out what was causing my problems.

I hope this helps others.

1 comment: