locked
Migrations RRS feed

  • Question

  • I have some class and Enable Migration

    then I Add in class property public DateTime Data { get; set; }

    and Add Migration

    then I try Update-Migration with default value

            

    public partial class MigrateDB : DbMigration
        {
            public override void Up()
            {
                AddColumn("dbo.Questions", "Data", c => c.DateTime(nullable: false, defaultValue:DateTime.Now.AddDays(-30)));
            }

            public override void Down()
            {
                DropColumn("dbo.Questions", "Data");
            }
        }

    But DataBase get exeption when I try Update-Datebase

    Conversion failed when converting date and/or time from character string.
    The statement has been terminated.

    WHY??????


    • Edited by Ahlompys Friday, March 31, 2017 3:13 PM
    Friday, March 31, 2017 3:11 PM

Answers

  • Hi Ahlompys,

    According to your description, I create a demo and reproduce your issue on my side. you could not set a string default value to a datetime field. please modify your migration code like this:

    public partial class MigrateDB : DbMigration
         {
             public override void Up()
             {
                 AddColumn("dbo.Questions", "Data", c => c.DateTime(nullable: false, defaultValueSql: "GETDATE()-30"));
             }
    
             public override void Down()
             {
                 DropColumn("dbo.Questions", "Data");
             }
         }

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, April 4, 2017 5:43 AM