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

c# ef-code-first entity-framework

Question

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. But.. This column will NOT be nullable, so I need to provide a default value of true to all the rows that currently exist.

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

IMPORTANT:

(This was in the OP, but people seemed to miss is.)

When databases are updated with the migration, all existing rows which receive this new column MUST have their values set to True.

1
20
12/2/2016 6:46:39 PM

Accepted Answer

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));
33
12/2/2016 6:54:35 PM

Popular Answer

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

This is will set the default value to true when this 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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow