Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database Generated Date on Insert with NHibernate

Tags:

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.

like image 969
Daniel Mahadi Avatar asked Jul 08 '09 04:07

Daniel Mahadi


3 Answers

You need an nHibernate Audit Interceptor:

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

like image 185
Robert Harvey Avatar answered Nov 19 '22 13:11

Robert Harvey


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.

like image 2
David Veeneman Avatar answered Nov 19 '22 13:11

David Veeneman


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);
like image 1
Guillermo Gutiérrez Avatar answered Nov 19 '22 12:11

Guillermo Gutiérrez