Moving Entity Infrastructure - Adding a New Column with a Value for Existing Entries

I have an application with Entity Framework Code First.

In the table, I need to add a column. So I added it to the model and created the migration.

But during the migration, I would like to update existing records and add value for this new column. This value should be taken from the database (a constant field in my "Configuration" table).

But the default value should only be applied to existing records, not the next one.

How can I do this from my migration class?

My current migration class:

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

Edit: still look for a solution to update all existing entries (using value 0), but only after this migration ...

+6
source share
1 answer

You just need to change the Up() method and include an SQL statement in it to set the column value in existing rows. This will only be done when updating the database, and the update is related to this particular migration. Thus, only when updating the Update-Database will only existing rows be updated.

Add code like this after the AddColumn command AddColumn that the column is already available in the table when you execute the SQL statement:

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

NOTE. (SELECT val FROM config) is a pseudo code that you should replace with a query that returns the desired value

+9
source

Source: https://habr.com/ru/post/979769/


All Articles