Kevin McKelvin

Introducing NHibernate 3 (Devs4Devs)

4 September 2010

Thanks to all who attended my 20 minute introduction to NHibernate 3 this morning. Here are my slides from the presentation

Introducing_NHibernate3.pptx

And the code samples:

Loquacious SessionFactory configuration

var config = new Configuration();

config.DataBaseIntegration(db =>
						   {
							   db.ConnectionStringName = "ConnectionString";
							   db.Dialect<MsSql2008Dialect>();
						   })
	.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>())
	.SetProperty(NHibernate.Cfg.Environment.CurrentSessionContextClass, "web")
	.AddAssembly(typeof (Artist).Assembly);

HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

return config.BuildSessionFactory();

Querying the Music Store

IMusicStoreContext context = MvcApplication.GetCurrentRequestSession();

using (var tx = context.Session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
    var artists = (from artist in context.Artists
                  where artist.Name.StartsWith("a")
                  orderby artist.Name descending
                  select artist).Fetch(x => x.Albums).ToList();

    tx.Commit();

    return View(artists);
}

One change I’ve made here is the call to .ToList() when selecting the artists. By enumerating the collection, we’re forcing NHibernate to get the objects from the database - to ensure that the select happens inside the transaction boundary.

The View code

<% foreach (var artist in Model)
   { %>

   <tr>
   <td><%: artist.Name %></td>
   <td><%: string.Join(", ", artist.Albums.Select(a => a.Title)) %></td>
   </tr>

<%
   } %>

Kevin McKelvin

These are the online musings of Kevin McKelvin. He is the CTO at Resource Guru, and lives in Newcastle upon Tyne, UK.