6

does anyone know a way how I could set through mapping the default value of a column so for e.g. when I generate DB from mappings I would have DateTime column having getdate() as default value?

I tried so far this (looks exactlly like what I need) but it doesn't work

this.Map(x => x.LastPersistedOn, "DateModified") 
    .Access.Property() 
    .Default("getdate()"); 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nikola Malovic
  • 1,230
  • 1
  • 13
  • 24
  • I have the same issue in fluent 1.0 and there does not seem to be a solution - you can do it through events but this is not always appropriate. Anyone else? – row1 Mar 09 '10 at 02:22
  • possible duplicate of [NHibernate + default getdate() column](http://stackoverflow.com/questions/1145197/nhibernate-default-getdate-column) – Kyle Hale Apr 24 '14 at 16:12

2 Answers2

6

I just tried setting some default values and it worked as expected. I am using Fluent as retrieve from Git the 24.05.2010 so updating your copy may solve your problem.
Mapping

public class SampleEntity
{
    public virtual DateTime DateTimeProperty { get; set; }
}

With

 public class SampleEntityMap
        : ClassMap<SampleEntity>
{
   public SampleEntityMap()
   {
    Map(x => x.DateTimeProperty, "DateTimeColumn")
             .Access.Property()  //actually not necessary 
             .Not.Nullable()
             .Default("getDate()");
   }
}

this will produce the following sql (from output to the console)

create table SampleEntity(
   DateTimeColumn DATETIME default  getDate()  not null
  )

--
Dom

Dom Ribaut
  • 198
  • 2
  • 8
4

The way to do this is to assign the current DateTime in code rather than using default value in the database. Then treat it as a normal column. Seemed a bit strange to me at first coming from a model-driven design background, but managing default values at the POCO level is the DDD way to do it.

Would be good to hear others' opinions too

  • 1
    The issue I have with this is it depends on the users clock. If not an end user if you have the application running in two different timezones it's already complicated enough. – hometoast Aug 18 '10 at 11:30
  • Something else to think about is existing data. I know this is an old post, but if you are adding a new field to an existing class/table/map you don't always want the default value to be what would normally be the defualt (for instance a boolean column that you want the default to be true in all existing records) – DevTheo Jan 28 '11 at 15:14