问题描述
我正在使用 EF6 在我的数据库中存储 report
类的实例.数据库已经包含数据.假设我想向 report
添加一个属性,
I am using EF6 for storing instances of the report
class in my database. The database already contains data. Say I wanted to add a property to report
,
public class report {
// ... some previous properties
// ... new property:
public string newProperty{ get; set; }
}
现在如果我去包管理控制台并执行
Now if I go to the package-manager console and execute
add-migration Report-added-newProperty
update-database
我将在/Migrations"文件夹中获得一个文件,将 newProperty
列添加到表中.这工作正常.但是,在数据库中较旧的条目上,newProperty
的值现在是一个空字符串.但我希望它是,例如,旧的".
I will get a file in the '/Migrations' folder adding a newProperty
column to the table. This works fine. However, on the older entries in the database, the value for the newProperty
is now an empty string. But I want it to be, e.g., "old".
所以我的问题是:如何在迁移脚本(或其他地方)中为新属性(任何类型)设置默认值?
So my question is: How do I set default values for new properties (of any type) in the migration script (or elsewhere)?
推荐答案
如果你看到生成的迁移代码你会看到 AddColumn
If you see the generated migration code you will see 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()"));
这篇关于代码优先迁移:如何为新属性设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!