Code-first migration: How to set default value for new property?(代码优先迁移:如何为新属性设置默认值?)
问题描述
我正在使用 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()"));
这篇关于代码优先迁移:如何为新属性设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代码优先迁移:如何为新属性设置默认值?


基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01