NHibernate identity columns that are not primary keys

Sometimes is useful to have an auto incrementing number for columns, say for example an OrderNumber.

If you are using NHibernate’s schema export functionality to generate your schema and you are not using the identity generator then you cannot use the identity generator outside for of the id mapping. If you are creating the database by hand it is typically pretty easy to assign an identity to column and set the seed and increment, but at first glance this does not look to be possible.

I started googling around and found this link:

http://weblogs.asp.net/bsimser/archive/2008/10/29/nhibernate-identity-columns-that-are-not-the-primary-key.aspx

Check out Fabio’s comments at the bottom.

Turns out its super easy. You just have to give NHibernate a bit more information about the column by adding a “column” section to the property.

OrderNumber Property Mapping

    <property name="OrderNumber" access="field.camelcase"  generated="insert" insert="false" update="false">
      <column name="OrderNumber" not-null="true" sql-type="int IDENTITY(1,1)" index="IDXOrderNumber"/>
    </property>

We tell NHibernate that the column is generated on insert and to not insert or update the column.
We also set the sql-type to be an IDENTITY(seed, increment) column.

Now when you generate the schema you will get an identity column.

OrderNumber

There are different and possibly better strategies to generate an order number, but this works pretty well without a lot of extra work.

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a0133ecbab7ab970b01348035c5a6970c

Listed below are links to weblogs that reference NHibernate identity columns that are not primary keys:

Comments

You can follow this conversation by subscribing to the comment feed for this post.

The comments to this entry are closed.