Kevin McKelvin

The NH3 Music Store Part 3

28 August 2010

The time’s come to start swapping out EF4 for NHibernate 3 query code. I’ve chosen to tackle the ShoppingCart class first before heading to the controllers.

There are a couple of key differences between NHibernate and Entity Framework. One that popped up immediately here is that NHibernate requires transactions to be controlled explicitly, while EF4 controls them implicitly. Each approach has its benefit, but in general I like the control that NHibernate provides.

I’m going to use the same LINQ queries where possible to query NHibernate as were used to query EF4 in the original code.

public int CreateOrder(Order order)
{
    using (var tx = storeDB.Session.BeginTransaction())
    {
        var cartItems = GetCartItems();

        //Iterate the items in the cart, adding Order Details for each
        foreach (var cartItem in cartItems)
        {
            var orderDetail = new OrderDetail
            {
                Album = cartItem.Album,
                Order = order,
                UnitPrice = cartItem.Album.Price
            };

            order.OrderDetails.Add(orderDetail);
        }

        //Save the order
        storeDB.Session.Save(order);
        tx.Commit();
    }

    //Empty the shopping cart
    EmptyCart();

    //Return the OrderId as a confirmation number
    return order.OrderId;
}

That’s the CreateOrder(Order) method on the ShoppingCart now with the NHibernate 3 changes I’ve made.

A few cleanups were possible here over the old EF4-based code. NHibernate 3 can do cascading saves, so I don’t need to expose OrderDetails as an entity on the IMusicStoreContext anymore, I can simply add the details to the Order and persist the Order – and NHibernate will handle the rest for me.

Code’s up on the GitHub Repo, only 12 more compiler errors now :) Progress!


Kevin McKelvin

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