我正在使用 EF6 在我的数据库中存储 report
类的实例。数据库已包含数据。假设我想向 report
添加一个属性,
public class report {
// ... some previous properties
// ... new property:
public string newProperty{ get; set; }
}
现在,如果我转到包管理器控制台并执行
add-migration Report-added-newProperty
update-database
我将在“/Migrations”文件夹中获取一个文件,将 newProperty
列添加到表中。这很好用。但是,在数据库中的旧条目上,newProperty
的值现在是一个空字符串。但我希望它是,例如,“旧”。
所以我的问题是:如何在迁移脚本(或其他地方)中为新属性(任何类型)设置默认值?
最佳答案
如果您看到生成的迁移代码,您将看到 AddColumn
AddColumn("dbo.report", "newProperty", c => c.String(nullable: false));
你可以添加defaultValue
AddColumn("dbo.report", "newProperty",
c => c.String(nullable: false, defaultValue: "old"));
或者添加defaultValueSql
AddColumn("dbo.report", "newProperty",
c => c.String(nullable: false, defaultValueSql: "GETDATE()"));
关于c# - 代码优先迁移 : How to set default value for new property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31025967/