c# - 代码优先迁移 : How to set default value for new property?

标签 c# .net entity-framework entity-framework-6 entity-framework-migrations

我正在使用 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/

相关文章:

C# RegEx 防止重复相同模式的贪婪匹配

c# - GC 没有完成 UserControl?

.net - 如何在 Linux 服务器上部署 .NET 项目(Webmin)

vb.net - 在 ODP.NET/EF 连接上使用 ALTER SESSION 进行不区分大小写的搜索?

c# - Entity Framework 错误 "You have an error in your sql syntax entity framework"

c# - 关于在哪里放置 Try 和 Catch 语句的问题

c# - ASP.NET Core 服务不创建 RabbitMQ 队列

c# - 对象初始值设定项和 Dispose 当属性可以抛出异常时

c# - 为什么 Stream.Read 不使用 out 参数?

c# - 数据未保存在数据库中(MVC3)