views:

224

answers:

1

What is the best way to generate a unique number for a business key?

In the example below, our customer wants a number (OrderNumber) they can use to refer to an Order.

<class name="Order">
  <id name="Id" ... />

  <property name="OrderNumber" column="order_number" />

</class>
+3  A: 

I've found that the best way to perform these tasks is to write them in code and not leak them into the data layer. I don't let NHibernate calculate it. I treat this concept as a fully fledged feature of the application. This is nice because I can write tests for it and have flexibility. Sometimes there are other factors involved in calculating the next sequence number, like a relationship to another entity. Maybe you want sequential order numbers within the realm of a client: 02-001, 02-002 for client 02 and 01-001, 01-002 for client 01.

So I promote the concept of a SequneceNumber to a domain model object, map it with NHibernate and do the logic on my side. Whenever I need a new one, I use an interface that looks something like

public interface ISequenceRepository
{
    string GetNextSequenceNumber(Customer customer);
}

And it manages the current sequence number in one record (per Customer) in a database table. Whenever I call this function it increments the place-keeper in the database and returns the value.

A factory depends on this interface and uses it to build up the objects that need a sequence number.

Matt Hinze
Great points Matt. Thank you.
Brian