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

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

    You can avoid using fields and take advantage of Auto-property initialization, a feature new in C# 6.

    This will set the default value to true when the column is added to your database.

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

    Edit to include @BrewMate's comment:

    If all of your values set to false when you update the database, make sure to have the JSON formatter handle default values. The JSON formatter will ignore default values by default and then your database is setting the boolean to its default value, false. See the link below, I would try Default as the enumeration: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm

提交回复
热议问题