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

前端 未结 5 597
孤独总比滥情好
孤独总比滥情好 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:33

    Another option is create a default constructor and set the properties with the default values you need:

    public class Revision
    {
        public Boolean IsReleased { get; set; }
    
        public Revision()
        {
            IsReleased=true;
    
        }
    }
    

    To set the values to true of the existing rows when you run Update-Database command, you could do this in your Configuration class:

    protected override void Seed(YourContext context)
    {
        var entities=context.Revisions.Where(r=>!r.IsReleased)
        foreach(var e in entities)
        {
          e.IsReleased=true;
         //context.Entry(e).State = EntityState.Modified; If you have disabled change tracking then add this line
        }
        context.SaveChanges();
    }
    

    Update

    If it is a new column you are adding via migration maybe you can also do this:

    AddColumn("dbo.Revisions", "IsReleased", c => c.Boolean(nullable: false, defaultValue: true));
    

提交回复
热议问题