如何在Code First模型中的布尔值上设置默认值? [英] How to set a default value on a Boolean in a Code First model?

查看:202
本文介绍了如何在Code First模型中的布尔值上设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的表/模型,我想在其中添加新的布尔值列。该表已经有数百行数据,我无法触摸现有数据。但是..此列将不可为空,因此我需要为当前存在的所有行提供默认值 true

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; }
    ....
}

重要提示:

(这是在OP中,但是人们似乎想念的是。)

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

随着迁移进行更新,所有接收此新列的现有行都必须将其值设置为True。

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

推荐答案

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

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

这篇关于如何在Code First模型中的布尔值上设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆