How to set a default value on a Boolean in a Code First model?

前端 未结 5 596
孤独总比滥情好
孤独总比滥情好 2020-12-31 00:13

I have an existing table / model into which I want to drop a new Boolean column. This table already has many hundreds of rows of data, and I can\'t touch the existing data.

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 00:49

    According to the MSDN, DefaultValueAttribute specifies the default value for a property. You can use DefaultValueAttribute as the following:

    public class Revision
    {
        ...
        [DefaultValue(true)]
        public Boolean IsReleased { get; set; } = true;
        ....
    }
    

    Furthermore you can use UP() method inside of DbMigration class as the following:

    public partial class InitializeDb : DbMigration
    {
        public override void Up()
        {
                CreateTable(
                "dbo.Revision",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        ...
                        IsReleased = c.Boolean(nullable: false, defaultValue: true),
                        ...
                    })
                .PrimaryKey(t => t.Id);
        }
    }
    

    You should add "defaultValue: true" by yourself.

提交回复
热议问题