代码优先迁移:如何设置新属性的默认值? [英] Code-first migration: How to set default value for new property?

查看:73
本文介绍了代码优先迁移:如何设置新属性的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF6在数据库中存储 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()"));

这篇关于代码优先迁移:如何设置新属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆