6

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.

Daniel Mahadi
  • 848
  • 1
  • 10
  • 14

3 Answers3

2

You need an nHibernate Audit Interceptor:

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
2

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.

David Veeneman
  • 18,912
  • 32
  • 122
  • 187
  • This is what we do, and we have an internal rule that any DateAdded and DateModified columns are done in this way. Simple and works. – Perhentian Sep 15 '09 at 20:10
1

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);
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116