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:


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"/>

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.


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


TrackBack URL for this entry:

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


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

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.


Post a comment