Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 7 set initial default value for DateTime column

I need to be able to set a DateTime column's initial value.

When I specify "getutcdate() or DateTime.UtcNow

entity.Property(e => e.ShipDate).DefaultValue("getutcdate()")
entity.Property(e => e.ShipDate).DefaultValue(DateTime.UtcNow)

and then run dnx . ef migration add InitialMigration EF generates a migration snapshot with:

b.Property<DateTime?>("ShipDate")
  .Required()
  .Annotation("Relational:ColumnDefaultValue", "getutcdate()")
  .Annotation("Relational:ColumnDefaultValueType", "System.String");

when I use DateTime.UtcNow...

b.Property<DateTime?>("ShipDate")
  .Annotation("Relational:ColumnDefaultValue", "635754129448768827")
  .Annotation("Relational:ColumnDefaultValueType", "System.DateTime");

and an initial migration:

ShipDate = table.Column(
  type: "datetime2", 
  nullable: false, 
  defaultValue: "getutcdate()"),

when I use DateTime.UtcNow...

ShipDate = table.Column(
  type: "datetime2", 
  nullable: true, 
  defaultValue: new DateTime(2015, 8, 17, 12, 55, 44, 876, DateTimeKind.Unspecified)),

It would seem like it has to work, but when I insert data into the table, the default value for the column is the 'instant' in which the timestamp was created.

Am I missing something?

ALSO, since in the same vein, how to specify the IDENTITY SEED in EF7?

Thanks

UPDATE After generating the sql script , with both options I get:

If using "getutcdate()":

[ShipDate] datetime2 DEFAULT 'getutcdate()',

which does not work because of the quotes

or if using DateTime.utcNow:

[ShipDate] datetime2 DEFAULT '2015-08-17 12:55:44.8760000'

which explains the static value I was getting.

I guess I can manage with this. Is this is a bug or is there a correct way of doing this? Thanks

like image 283
dcga Avatar asked Aug 17 '15 11:08

dcga


1 Answers

You want to set the default value SQL, not a constant value:

entity.Property(e => e.ShipDate).HasDefaultValueSql("getutcdate()");
like image 67
bricelam Avatar answered Sep 22 '22 13:09

bricelam