NHibernate + default getdate() column

2019-04-16 17:46发布

问题:

How do I configure NHibernate to create the db schema with a column like this:

create_dt datetime not null default getdate()

I have this in the mapping file:

<property name="create_dt" update="false" insert="false" generated="insert" not-null="true" />

Is there anyway I can inject the sql server specific default getdate(). The documentation for generated properties even mentions this is how you handle a create_date field. I'm just not sure how to make my db schema generate properly. Will I have to edit the create table scripts manually?

Similar question.

EDIT: I figured out I can always change the table schema like so:

<database-object>
    <create>ALTER TABLE Report ADD CONSTRAINT DF_report_create_dt DEFAULT getdate() FOR create_dt;</create>
    <drop></drop>
  </database-object>

and I could add a trigger in the same way for an update_dt type of field. This seems better than supplying explicit insert and update statements that use getdate().

回答1:

I alway prefer to use the NHibernate Event system to set my audit properties like created date or update date. (See event system documentation here).

I prefer this approach because it keeps the logic out of my database layer but also it gives me the ability to have a single location in my code that is responsible for setting these values. And if I have a common base class for all my entities then I can even guarantee consistent behavior throughout my domain.



回答2:

this is an answer on a thread for Hibernate... it should port over to nHibernate without changing it...

https://forum.hibernate.org/viewtopic.php?f=25&t=996901&view=previous

please see the last post.

Failing that, i always generate the "date created" of an object in the constructor of the class:

public class MyClass
{
    private DateTime createdDate;

    public MyClass()
    {
        createdDate = DateTime.Now;
    }
}