我有一个现有的表/模型,我想在其中添加一个新的布尔列。该表已经有数百行数据,我无法触及现有数据。但是.. 该列不能为空,因此我需要为当前存在的所有行提供默认值
true
。
public class Revision
{
...
public Boolean IsReleased { get; set; }
....
}
重要:
(这是在OP中,但人们似乎错过了。)
通过迁移更新数据库时,接收此新列的所有现有行必须将其值设置为 True。
您可以避免使用字段并利用“自动属性初始化”,这是 C# 6 中的一项新功能。 将列添加到数据库时,这会将默认值设置为
true
。
public class Revision
{
...
public Boolean IsReleased { get; set; } = true;
....
}
编辑以包含@BrewMate
的 评论:
如果更新数据库时所有值都设置为 false,请确保让 JSON 格式化程序处理默认值。默认情况下,JSON 格式化程序将忽略默认值,然后您的数据库会将布尔值设置为其默认值false
。请参阅下面的链接,我将尝试使用 Default 作为枚举:
http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm
public class Revision
{
public Boolean IsReleased { get; set; }
public Revision()
{
IsReleased=true;
}
}
要在运行
true
命令时将值设置为现有行的
Update-Database
,您可以在 Configuration
类中执行此操作: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();
}
更新
AddColumn("dbo.Revisions", "IsReleased", c => c.Boolean(nullable: false, defaultValue: true));
MSDN,DefaultValueAttribute 指定属性的默认值。您可以使用 DefaultValueAttribute 作为 以下:
public class Revision { ... [DefaultValue(true)] public Boolean IsReleased { get; set; } = true; .... }
此外,您可以在 DbMigration 类中使用 UP() 方法,如下所示:
public partial class InitializeDb : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Revision",
c => new
{
Id = c.Int(nullable: false, identity: true),
...
IsReleased = c.Boolean(nullable: false, defaultValue: true),
...
})
.PrimaryKey(t => t.Id);
}
}
您应该自己添加“defaultValue: true”。
true
。
private Boolean _isReleased = true;
public Boolean IsReleased
{
get
{
return _isReleased;
}
set
{
_isReleased = value;
}
}