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

.net c# ef-migrations entity-framework entity-framework-6

Question

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, 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)?

1
45
6/30/2016 12:26:49 AM

Accepted Answer

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()"));
72
7/24/2016 2:13:21 PM

Popular Answer

You have to change the line in your migration script which adds the the property/column like this:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow