Unique number counter system using SQL Server identity fields and Fluent NHibernate

**UPDATE – As we moved forward with our project this method turned out to be a little less awesome than I thought when I put it together.   I’ve left this post here though as I am not ashamed of my failures! There is also some neat stuff in here with setting up the identity fields using nHibernate.

Recently I needed to create a generic re-usable system to generate system wide unique counters using SQL server tables and identity fields to handle the number generation.  One of the key requirements was to be able to specify the identity seed, but in a re-usable way of course.

Generic Class and Class Map

So lets start this off with a base class to define the counter object:

namespace GenericCounter { /// <summary> /// Define the attributes of a generic counter /// </summary> /// <remarks></remarks> /// <example> /// <code> /// </code> /// </example> public class CounterObject { private Int32? _counter; /// <summary> /// The unique key value distinguishing this counter object from all other instances of the same class. /// </summary> /// <remarks>NHibernate only allows one key per table and requires that a field be set as key. It cannot be the Identity field</remarks> public virtual Guid ID { get; protected set; }   /// <summary> /// Gets or sets the counter. /// </summary> /// <value>The counter value which will be generated by SQL server</value> /// <remarks></remarks> public virtual int? Counter {get { return _counter; } protected set { _counter = value; }} } }

.csharpcode, .csharpcode pre


font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/


.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt


background-color: #f4f4f4;

width: 100%;

margin: 0em;


.csharpcode .lnum { color: #606060; }

The first thing you will notice is that we’ve defined two fields.  One field guid and one field as  a nullable Int32.  Fluent NHibernate needs a key field for this table and to do the trickery that comes next it cannot be our identity based field.  Next lets setup a generic fluent mapping:

Page 1 of 3 | Next page