Added New Column to Database and Update My Model But I want to Update already existing rows because new Column is Added

StackOverflow https://stackoverflow.com/questions/23655212

  •  22-07-2023
  •  | 
  •  

Question

Added New Column to Database and Update My Model But I want to Update already existing rows because new Column is Added.

id|Name City
1 |A   |Null
2 |B   |Null
3 |C   |Null

I want to Set this City Column Programmetically It is work fine for new entries add For Example if Create View Render it sets the City Column but i want to set it for all ready existing rows.

Was it helpful?

Solution

If you are using automatic migrations:

You can use [DefaultValue] attribute when you adding new field.

Or:

You can run update SQL-script:

UPDATE table_name
SET City='SomeDefaultValue'
WHERE City = NULL;

If you are using custom code-based migrations:

When you creating migration for your database, you will got something like:

 public override void Up()
 {
     AddColumn("dbo.someTable", "City", c => c.String(nullable: false, defaultValue: "SomeDefaultValue"));    
 }   

In action parameter you have one of the options: defaultValue, this value will be used for all existing rows.

May be useful:

DefaultValueAttribute Class

Code-based Migrations

Entity Framework Code First: Migrations

Automatic Code First Migrations

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top