16 February 2008

NHibernate in Visual Web Developer Express

If you fancy using NHibernate in VWD you'll have trouble because you can't compile your mapping files into the same assembly as your classes. As a result you can't add mappings to your session factory by assembly name or class name.

Thankfully there is a simple solution to this, which I'll demonstrate with the aid of the quickstart example in the NHibernate documentation.

Start by creating all your persistance class files in your App_Code folder with your mapping files (.hbm.xml) alongside. Next, make the alterations to your web.config as outlined in section 1.1 of the quickstart but leave out this line:

<mapping assembly="QuickStart" />

In your mapping files, change the assembly attribute of the root hibernate-mapping element to "App_Code" and remove the namespace attribute if you're not using a namespace (the default behaviour of VWD) e.g:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="App_Code">

Finally, copy the code for the NHibernateHelper class from section 1.4 and change its constructor from this:

static NHibernateHelper()
{
   sessionFactory = new Configuration().Configure().BuildSessionFactory();
}

to this:

static NHibernateHelper()
{
   Configuration cfg = new Configuration().Configure();
   cfg.AddDirectory(new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(@"~/App_Code/")));
   sessionFactory = cfg.BuildSessionFactory();
}

The original constructor used the mapping element in the web.config to find out which mappings to load, here we're telling it to load all the mapping files it finds in the App_Code folder. You can also use the AddFile method to add individual mapping files.

4 comments:

Dirk-Jan said...

Hi Derek,

Thanx for this example! Since I'm not a 'real' programmer and simply want to make a proof of concept, I would like to do the same thing using Visual Basic instead of C#.
How should I translate the NHibernateHelper class from C# to VB ?

Derek Fowler said...

You might find this page useful, just paste in the C# and it will convert it to VB.NET (or vice versa).

Sam said...

Did you have any problems with a Security Exception (System.Security.Permissions.FileIOPermission) when you moved it to IIS? I've tried full trust and it still bombs on config.AddDirectory.

Unknown said...

Well i also get the security exception.

It points me to this line: sessionFactory = cfg.buildsessionFactory();

I you think the error might generated because of my web.config implementation.

Waiting to hear your reply!

Best regards