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()"));
这篇关于代码优先迁移:如何为新属性设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代码优先迁移:如何为新属性设置默认值?
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
