I was reading about NHibernate in the last 3-4 days. When i heard that LINQ2SQL will not be supported anymore, i was looking for a good ORM tool, and i decided to give a try to NHibernate. I just went to its website and downloaded version 2.0.1. I decided to write a very simple insert operation using NHibernate so i opened up many websites talking about NHibernate tutorials and tried to copy the code. I got so many errors :) that one time i decided to give up. One major problem i had was the configuration settings, unfortunately NHibernate wasn't throwing good error message so it took me sometime to figure out that configuration settings for NHibernate 2.0.0.1 is different than older versions, so here is a sample configuration file i have in my app.config that works :)
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate"/>
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2005Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=acm48_89\SQL;Integrated Security=True; initial catalog=StudentsDB
</property>
</session-factory>
</hibernate-configuration>
</configuration>
After i set this up, i got my second error :), which was basically telling me that NHibernate can’t find the property in my class. My class was partially like this:
public class Student
{
public int SID { get; set; }
public string FirstName{ get; set; }
public string LastName { get; set; }
…
and my mapping xml was:
<class name="Student" table="Students">
<id name="SID" access="field" column="SID">
<generator class="native"/>
</id>
<property name="FirstName" access="field" column="FName"/>
<property name=”LastName access=”field” column=”LName”/>
</class>
NHibernate was telling me that it can’t find any of these properties :), so i tried to read the documentation and it was really boring, and for some reason i don't remember, i decided to remove access=”field” section from the mapping and xml, and boom, this error message disappeared and i got my third error message :) which this time was more self explanatory: The properties has to be virtual.. This was easy fix for me as i read that, to support lazy loading, you have to mark you fields as virtual. I didn't want to have lazy loading for this simple project, so i added the key to mapping xml to turn off the lazy loading which is simply :lazy="false"
i think i am kind of having fun for now while i am learning NHibernate but i will use code smith to derive my classes and configuration settings once i get familiar doing them manually.
Tags: