The NHibernate 3 Music Store – Mappings and the first glimpse! – Part 6
29 August 2010
Having sorted out the infrastructure issues of changing EF4 out with NHibernate, the last bit of the job is to map all of the entities. There are a few ways I can accomplish this: XML files, Fluent NHibernate or Fabio Maulo’s ConfORM.
Despite the fact that I really hate writing xml, I still prefer using the .hbm.xml files over the other options. The NHibernate guys have made it really easy to write these xml files – like an XSD to provide IntelliSense and reasonable default values for non-essential properties.
I’m not going to post all of the XML here (it’s all on GitHub), here’s just one sample that maps the Album class.
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.2"
assembly="Mvc Music Store"
namespace="MvcMusicStore.Models">
<class name="Album">
<id name="AlbumId">
<generator class="identity" />
</id>
<many-to-one name="Genre" column="GenreId" />
<many-to-one name="Artist" column="ArtistId" />
<property name="Title" />
<property name="Price" />
<property name="AlbumArtUrl" />
<bag name="OrderDetails" cascade="all">
<key column="AlbumId" />
<one-to-many class="OrderDetail"/>
</bag>
</class>
</hibernate-mapping>
So at this point the solution is compiling and runs, I’ve got one last problem to iron out however. NHibernate doesn’t like this LINQ query on the HomeController:
return storeContext.Albums
.OrderBy(a => a.OrderDetails.Count())
.Take(count)
.ToList();
To get this to work I’ve changed the query around to use the QueryOver API
return storeContext.Session.QueryOver<Album>()
.Fetch(x => x.OrderDetails).Eager
.List<Album>()
.Take(count)
.ToList();
I know this isn’t ideal, unbounded result sets everywhere, however I’m more interested in getting the system to work in the first place than performance at this point. That aside, the query that EF4 generates here is just as bad. If there are any suggestions, I’d love to see how you’d write this query.
So, holding thumbs I hit F5 again, and here’s what we get:
Tada! :D In my brief explorations I haven’t found anything that is not working. I still have to do quite a bit of work to know for sure.
But for now (at least until I get more time to test this) that’s the NHibernate 3 ASP.NET MVC Music Store! There are still a few issues to iron out with the NHibernate implementation. I’ve had a lot of fun and learnt a heck of a lot in the last bit while working on this and writing about it.
All of the code is available on GitHub at http://github.com/kmckelvin/NH3-MusicStore. Please go check it out, any feedback and constructive criticism is most welcome.