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

前端 未结 7 896
轻奢々
轻奢々 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.

    0 讨论(0)
  • 2020-11-28 10:50

    Alternatively if your entities inherit from a common interface you can override the SaveChanges method on the DbContext and set or update properties at that point (great for Created Date and Last Changed Date)

    0 讨论(0)
  • 2020-11-28 10:52

    An improvement: check if the constraint exists:

    Sql(@"
    if not exists (
        select *
          from sys.all_columns c
          join sys.tables t on t.object_id = c.object_id
          join sys.schemas s on s.schema_id = t.schema_id
          join sys.default_constraints d on c.default_object_id = d.object_id
        where 
          d.name = 'DF_ThubOutputEmail_Created'
    )
    begin
        ALTER TABLE dbo.ThubOutputEmails ADD CONSTRAINT DF_ThubOutputEmail_Created default getdate() for Created;
    end");
    
    0 讨论(0)
  • 2020-11-28 10:54

    Create a migration:

    public partial class Table_Alter : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.tableName", "columnName", 
               c => c.DateTime(nullable: false, defaultValueSql: "GETDATE()"));
        }
    
        public override void Down()
        {
            DropColumn("dbo.tableName", "columnName");
        }
    }
    

    For existing records it will set the datetime when you will run Update-Database command, for new records it will be set the datetime of creation

    0 讨论(0)
  • 2020-11-28 11:09

    This is the most simple way.

    First Add DatabaseGeneratedOption.Computed DataAnnotion to your property

    and now you can modify de SqlServerMigrationSqlGenarator, override Genarate method and set the DefaultValueSql = "GETDATE()" or "GETUTCDATE()";

    0 讨论(0)
  • 2020-11-28 11:13

    You must use custom SQL script in Up method for setting default value:

    Sql("ALTER TABLE TableName ADD CONSTRAINT ConstraintName DEFAULT GETDATE() FOR ColumnName");
    

    Setting default value in code allows only static values - no database level functions.

    Anyway setting it in POCO constructor is correct way if you are going to use code first. Also if you want to set the value in the application for some special cases you cannot use a default value in the database because the default value in the database requires either DatabaseGeneratedOption.Identity or DatabaseGeneratedOption.Computed. Both these options allow setting the property only in the database.

    Edit:

    Since the product is still in development my answer is no longer valid. Check @gius answer for actual way to achieve this requirement by using defaultValueSql (it wasn't available in EF Migrations Beta 1 but was added in EF 4.3 Beta 1 which already includes migrations).

    0 讨论(0)
提交回复
热议问题