views:

1083

answers:

1

Is it possible to have an integer property of a class auto increment managed by the database but not be a primary key (or Id as NHibernate refers to them)? I'm having trouble finding examples of how to do this. Any help would be appreciated. Thanks.

+2  A: 

Two options.

  • if the database is 100% responsible for this you just need to tell NHibernate that the property is generated and not to include it in any updates/isnerts. The downside is that NH will need to do an additional select to keep the value fresh in memory.

    < property name="Foo" generated="always" update="false" insert="false" />

  • if the database is not responsible and you just want to have this done automatically you can use an interceptor to set the value to 1 on an insert and to increment it by 1 on an update.

http://www.nhforge.org/doc/nh/en/index.html#objectstate-interceptors (11.1 - Interceptors)

You would override OnSave() to find the property and set the initial value and then override OnFlushDirty() to find the property property and increment.


Edit:

I'm an idiot, didn't notice you said Fluent NHibernate.


Edit #2:

I think you might also be interested in using this column as a versioning?

< version name="Foo" generated="always" />
eyston
Don't worry, it's almost the same.Map(x => x.Foo).ReadOnly().SetAttribute("generated", "always");The SetAttribute will be replaced by Generated.Always when we hit 1.0.
James Gregory
I downloaded the latest FNH and was sort of confused by .Update() not taking a parameter. I wasn't sure what that would end up as in the mapping. ReadOnly() makes sense though.
eyston