Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 264
EluciusFTW Avatar asked Jun 24 '15 12:06

EluciusFTW


People also ask

How do I set default value in property?

Set a default valueRight-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

Can we set default value in property C#?

You can assign the default value using the DefaultValueAttribute attribute, as shown below.

Does Entity Framework have default value?

The Entity Framework Core Fluent API HasDefaultValue method is used to specify the default value for a database column mapped to a property. The value must be a constant.


2 Answers

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()")); 
like image 137
Hamid Pourjam Avatar answered Oct 05 '22 14:10

Hamid Pourjam


Hope it helps someone. Putting everything together from previous answers (example using a boolean property):

1) Add a new property to the entity.

/// <summary> /// Determines if user is enabled or not. Default value is true /// </summary> public bool IsEnabled { get; set; } 

2) Run the command below to add the new change in the migrations.

add-migration addIsEnabledColumn 

3) A migration file is created from the command above, open that file.

enter image description here

4) Set the default value.

public override void Up() {         AddColumn(             "dbo.AspNetUsers",              "IsEnabled",              c => c.Boolean(                 nullable: false,                  defaultValue: true             )         ); } 
like image 27
Victor LG Avatar answered Oct 05 '22 13:10

Victor LG