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()"));
这篇关于代码优先迁移:如何为新属性设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代码优先迁移:如何为新属性设置默认值?
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
