fluent nhibernate auto increment non key (Id) property

前端 未结 2 876
-上瘾入骨i
-上瘾入骨i 2020-12-31 07:06

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 trou

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 07:40

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

提交回复
热议问题