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)?
I found that just using Auto-Property Initializer on entity property is enough to get the job done.
For example:
If you see the generated migration code you will see
AddColumn
You can add
defaultValue
Or add
defaultValueSql
I have resolved this problem by overriding the SaveChanges method. See below for my solution.
Solution Explain
i) Override the SaveChanges method in the DbContext class.
ii) Write logic to set default values
Example
Hope it helps someone. Putting everything together from previous answers (example using a boolean property):
1) Add a new property to the entity.
2) Run the command below to add the new change in the migrations.
3) A migration file is created from the command above, open that file.
4) Set the default value.
You have to change the line in your migration script which adds the the property/column like this: