views:

1069

answers:

2

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

+2  A: 

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&amp;t=996901&amp;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;

}

}

alex
+1 for doing it in the domain instead of the database
mxmissile
I guess it's just too database specific. I suppose I'd have to use the custom update query to handle an _update_dt_ column. I'll probably just edit the create scripts for the _create_dt_ columns.
dotjoe
Could someone explain why it's better to do it in the domain? I can only think of bad things such as the wrong system time and it's never going to be as exact as getdate().
dotjoe
+2  A: 

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.

Andrew Hanson
The event system seems cool. I'd still prefer to use the db's date and I think I could do it by simply using a "select getdate()" to fetch the current date from db. This is the way to go, I don't want to copy that same logic to every table with those fields.
dotjoe
thanks, I went the events route. very nice! now I need to figure out how to inherit mapping files...
dotjoe
Have you looked at http://fluentnhibernate.org for defining your mappings? If you're just looking at mapping inherited classes you can use the subclass element.
Andrew Hanson