The McDev Blog

Kevin McKelvin's perspective of the Ruby world.

The NH3 Music Store Part 3

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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!