Entity framework migration - add new column with a value for existing entries

c# ef-code-first ef-migrations entity-framework


With Entity Framework Code First, I have a program.

I need to add a column to a table. Therefore, I developed a Migration and put it to the model.

However, I would like to update the current entries and add a value for this new column during the migration. The database must be used to retrieve this value (a constant field in my "Configuration" table).

But the following entry shouldn't use the default value; rather, it should only be used for existing entries.

What steps should I take from my Migration class?

My migration class right now is:

public override void Up()
    var theDefaultValue = MyConstants.MyConstantParameterFromDatabase;
    AddColumn("MySchema.MyTable", "MyNewColumn", c => c.Decimal(nullable: false, precision: 18, scale: 2));

Edit: Still searching for a way to update every entry that now has a 0 value, but only following this migration...

12/17/2014 4:18:49 PM

Popular Answer

All you have to do is change theUp() Include a SQL statement in the method to set the column value in the existing rows. Only when the database is updated and the update includes this specific Migration will this be carried out. As a result, only the rows that currently exist will be changed when theUpdate-Database is sounded.

add this code after theAddColumn the field is already present in the table when the SQL statement executes by running the following command:

Sql("UPDATE dbo.MyTable SET Column = (SELECT val FROM config)");

NOTE: (SELECT val FROM config) replaces the pseudocode with a query that returns the desired value.

3/6/2016 11:14:01 AM

Related Questions


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