Fluent migrator. How to add datetime column with default values as current date?
Asked Answered
C

2

25

How can I alter column in fluent migration with default date time value that is current date time?

So I need smth like this:

ALTER TABLE database ADD column DATETIME DEFAULT GETDATE() NOT NULL;

only for fluent migration. Thanks.

Crass answered 5/1, 2013 at 12:57 Comment(1)
Great answer after short investigation: you should use extension method WithDefault(SystemMethods.CurrentDateTime) where SystemMethods can be one of: CurrentDateTime, CurrentUTCDateTime, NewGuid, NewSequentialId.Crass
B
11

You probably have already found the documentation for SystemMethods on the wiki. I just updated it so that it reflects the latest version of FluentMigrator.

Just want to point out that these are database-specific and only Sql Server has all five SystemMethods implemented. This makes your migrations less portable as it is no longer standard sql that is generated and some of the SystemMethods are not supported for other databases (CurrentUser does not seem to be possible in MySql for example).

If you see the need for any others then please log it as an issue on FluentMigrator's Github site and we'll try and add it in.

Built answered 6/1, 2013 at 14:17 Comment(0)
I
24

Seeing as the answer doesn't actually include any code:

Create.Table(nameof(Report))
      .WithColumn(nameof(Report.Id)).AsInt32().NotNullable().PrimaryKey().Identity()
      .WithColumn(nameof(Report.CreatedAt)).AsDateTime().Nullable()
                                           .WithDefault(SystemMethods.CurrentDateTime);

The WithDefault(SystemMethods) method is the solution.

Irrepealable answered 18/3, 2016 at 17:27 Comment(2)
There is one issue with this answer. OP also wants a not null column.Pilgarlic
Switch to NotNullable()Irrepealable
B
11

You probably have already found the documentation for SystemMethods on the wiki. I just updated it so that it reflects the latest version of FluentMigrator.

Just want to point out that these are database-specific and only Sql Server has all five SystemMethods implemented. This makes your migrations less portable as it is no longer standard sql that is generated and some of the SystemMethods are not supported for other databases (CurrentUser does not seem to be possible in MySql for example).

If you see the need for any others then please log it as an issue on FluentMigrator's Github site and we'll try and add it in.

Built answered 6/1, 2013 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.