Introducing NHibernate 3 (Devs4Devs)

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


And the code samples:

Loquacious SessionFactory configuration

var config = new Configuration();

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


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();


    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)
   { %>

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

   } %>