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

前端 未结 7 997
轻奢々
轻奢々 2020-11-28 10:20

I added EntityFramework.Migrations (Beta 1) to an existing Code-First app that is going through some changes (for both migration capabilities and more fine-tuning of the tab

7条回答
  •  半阙折子戏
    2020-11-28 10:49

    You can use

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

    Usage:

    public partial class MyMigration : DbMigration
    {
        public override void Up()
        {
            CreateTable("dbo.Users",
                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.

提交回复
热议问题