Possible to default DateTime field to GETDATE() with Entity Framework Migrations?

You can use

DateCreated = c.DateTime(nullable: false, defaultValueSql: "GETDATE()")


public partial class MyMigration : DbMigration
    public override void Up()
            c => new
                    Created = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"),
            .PrimaryKey(t => t.ID);

Update 2012-10-10:

As requested by Thiago in his comment, I add a little extra context.

The code above is a migration-file generated by EF Migrations by running Add-Migration MyMigration as a command in the package manager console. The generated code is based on the models in the DbContext associated with migrations. The answer suggests that you modify the generated script so that a default value is added when the database is created.

You can read more about Entity Framework Code First Migrations here.

Leave a Comment