且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Code First模型中的布尔值上设置默认值?

更新时间:2023-10-15 16:06:58

创建另一个选项默认构造函数,并使用所需的默认值设置属性:

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;

    }
}

将值设置为 Update-Database 命令时,对现有行中的c $ c> true 行操作,可以在 Configuration中执行此操作类:

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));