Entity Framework Code first making a column non-nullable

后端 未结 2 820
北荒
北荒 2021-02-05 07:17

I am using EF code first for my project. I have following code in my DataModel

[HiddenInput(DisplayValue = false)]        
public DateTime? PasswordDate { get; s         


        
2条回答
  •  梦如初夏
    2021-02-05 07:44

    It's not possible to directly add a non-nullable column to a table that has historical data in the table if no default value is provided for that column.

    What I do is

    1. add the column as nullable.
    2. provide an sql script to populate this newly added column.
    3. alter the column to make is as non-nullable.

    Code example(with postgres database):

     public override void Up()
        {            
            AddColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: true));
            Sql(@"UPDATE ""public"".""YourTableName""
                  SET ""YourColumnName"" = Value you want to set
                ");
    
            AlterColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: false));
        }
    

提交回复
热议问题