first migration: How to set default value for new property?

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

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, eg, "old".

So my question is: How do I set default values for new properties (of any type) in the migration script (or elsewhere)?


If you see the generated migration code you will see AddColumn

AddColumn("dbo.report", "newProperty", c => c.String(nullable: false));

You can add defaultValue

AddColumn("dbo.report", "newProperty", 
           c => c.String(nullable: false, defaultValue: "old"));

Or add defaultValueSql

AddColumn("dbo.report", "newProperty",
           c => c.String(nullable: false, defaultValueSql: "GETDATE()"));

您必须在您的迁移脚本中更改行,并添加属性/列,如下所示:

AddColumn("dbo.reports", "newProperty", c => c.String(nullable: false, defaultValue: "test"));

I found that just using Auto-Property Initializer on entity property is enough to get the job done.

For example:

public class Thing {
    public bool IsBigThing { get; set; } = false;
}
链接地址: http://www.djcxy.com/p/24712.html

上一篇: SQL触发器,检查是否输入了某个值

下一篇: 第一次迁移:如何为新的属性设置默认值?