NHibernatin' composite ids

So I tryed my way with NHibernate today, just doing some plain-old CRUD stuff. So I hooked up ye ol’ Norhtwind Database and tryed to create some objects. Ok, so I came up with Customers, Orders, OrderItems (called Order Details in the database) and Products. But wait – there is a slight problem: OrderItems has a so called composite-id. Although this is covered by NHibernate, this took quite a while to figure out. First of all I had to create the correct mapping file:

<?xml version='1.0' encoding='utf-8'?>
<hibernate-mapping
assembly=Business'
namespace=Business'
xmlns='urn:nhibernate-mapping-2.2'>
<class name='OrderItem'
table='[Order Details]'>
<composite-id>
<key-many-to-one name='Order'
column='OrderID'
class='Business.Order, business' />
<key-many-to-one name='Product'
column='ProductID'
class=Business.Product, business'/>
</composite-id>
<property name='UnitPrice'/>
<property name='Quantity'/>
<property name='Discount'/>
</class>
</hibernate-mapping>

After compiling this, I got a nice little error, telling me, that I should override the Equals() method. Ok, so I did how I was told, and came up with:

public override bool Equals(object obj)
{
//return base.Equals(obj);
OrderItem other = obj as OrderItem;
if (other != null) return (order.Id == other.order.Id) && (product.Id == other.product.Id);
else return false;
}
public override int GetHashCode()
{
//return base.GetHashCode();
return order.Id.GetHashCode() & product.Id.GetHashCode();
}

This finally did it 🙂

Leave a Comment.