Daniel Mahadi
Daniel Mahadi

Reputation: 918

Database Generated Date on Insert with NHibernate

I am a newbie with NHibernate, so please bear with me.

Let's imagine, i have a property for CreatedDate, and i wanted it to be filled with the sql server datetime value.

The possible solution that i found out is, to mark this property as "generated=always" with "insert=false" and "update=false", and then set the default value for the CreatedDate on sql server level (i mean the database column), to "Getdate()".

Is this the right approach? Thanks for your time, any suggestion will be well appreciated.

Upvotes: 6

Views: 3873

Answers (3)

Guillermo Gutiérrez
Guillermo Gutiérrez

Reputation: 17799

You could map the property as a Datetime. Then, before any insert/update, you can get the date from database, like this:

myEntity.LastModifiedDate = Session.CreateSQLQuery("SELECT GETDATE()").UniqueResult<DateTime>();
Session.SaveOrUpdate(myEntity);

Upvotes: 1

David Veeneman
David Veeneman

Reputation: 19122

Another solution is to insert the date in SQLServer, when the record is created. Make the column non-nullable, and set its default value to the SQL functon GETDATE(). When the record is created, it will be date/timestamped. Map it in NHibernate like any other DateTime property.

Upvotes: 2

Robert Harvey
Robert Harvey

Reputation: 180788

You need an nHibernate Audit Interceptor:

http://fgheysels.blogspot.com/2008/07/nhibernate-iinterceptor.html

Upvotes: 2

Related Questions