views:

467

answers:

1

I'm using the SchemaExport class in NHibernate to generate my database from my .hbm.xml files. Is there a way to set the Identity Seed on my tables to 0 rather than 1? For ref tables, I prefer to have all my initial status ids set to 0, and I don't want to have to reset this value every time I regenerate my DB while in dev. I'm using SQL Server 2005, NHibernate version 1.2.1.

+2  A: 

It's best NOT to use Identity columns with NHibernate if possible; They cause NHibernate to make more trips to the database, make batching impossible, and essentially break the Unit of Work pattern. This is discussed on nhforge.org and in a few blog posts like this one. Guid.comb or Hi-Lo is usually a better option.

If you really want to continue using Identity, and have it seed from 0, then here's some possibilities (not tested).

Just a guess, but you'd probably need to first set your unsaved-value="-1" like this:

This allows NHibernate to know that an identity of -1 means the object is not saved (transient).

You would also need to ensure that all Entities id's have a default value of -1 also (numbers obviously default to 0):

public class Order {
    public virtual long Id{get; private set;}
    public Order(){
      Id = -1;
    }
}

It's pretty yukky! Then it's a matter of figuring out how to get SchemaExport to seed from 0. It may do this already (by using unsaved-value +1 as the seed)? Check to see if it work. If not, then you might need to look at patching it or overriding the hbm.xml. One way would be to use XSLT to transform the generated HBM files. Again, pretty yukky.

Tobin Harris
You're right, this is an ugly process. I think a refactor is in order. Thanks for the advice.
Mark Struzinski