使用NHibernate插入数据库生成的日期

时间:2022-08-24 15:49:15

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

我是NHibernate的新手,所以请耐心等待。

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

让我们想象一下,我有一个CreatedDate属性,我希望它填充sql server datetime值。

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()".

我发现可能的解决方案是,使用“insert = false”和“update = false”将此属性标记为“generated = always”,然后在sql server级别设置CreatedDate的默认值(我的意思是数据库)列),“Getdate()”。

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

这是正确的方法吗?感谢您的时间,任何建议将不胜感激。

3 个解决方案

#1


You need an nHibernate Audit Interceptor:

你需要一个nHibernate审计拦截器:

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

#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.

另一种解决方案是在创建记录时在SQLServer中插入日期。使列不可为空,并将其默认值设置为SQL functon GETDATE()。创建记录时,它将是日期/时间戳。像任何其他DateTime属性一样在NHibernate中映射它。

#3


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

您可以将该属性映射为Datetime。然后,在任何插入/更新之前,您可以从数据库中获取日期,如下所示:

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

#1


You need an nHibernate Audit Interceptor:

你需要一个nHibernate审计拦截器:

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

#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.

另一种解决方案是在创建记录时在SQLServer中插入日期。使列不可为空,并将其默认值设置为SQL functon GETDATE()。创建记录时,它将是日期/时间戳。像任何其他DateTime属性一样在NHibernate中映射它。

#3


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

您可以将该属性映射为Datetime。然后,在任何插入/更新之前,您可以从数据库中获取日期,如下所示:

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