I have a table which contains two columns (A and B).column A has default value of 1 or 0. I want to add new column C, its default value is 0 and C'values depends on A'value.
How can I do that using migration in ASP.NET Core.
Asked
Active
Viewed 1,544 times
0
-
2Read the part about computed columns [here](https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations). – user18387401 Jul 02 '22 at 11:14
-
"add new column C, its default value is 0 and C'values depends on A'value."Do you mean copy data from one column to another in the same table? If so, see this [answer](https://stackoverflow.com/questions/6308594/how-can-i-copy-data-from-one-column-to-another-in-the-same-table) – Qing Guo Jul 05 '22 at 01:59
2 Answers
1
At first define your columns in a class for example named "Sample", than define a dbSet property in your application context , something like this
public DbSet<Sample> Contacts { get; set; }
If you want to set default value for your columns you can override OnModelCreating method in your application context and set a default value for your columns , like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Sample>()
.Propery(p => p.A)
.HasDefaultValue(0);
}
In above code "A" is your intended column name .
Than write Add-Migration
in command console to create new migration , than write Update-Database
.
Hope it will be useful for you

Apollo13
- 11
- 6
0
try something like this :
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "C",
table: "MyTableName",
nullable: false);
migrationBuilder.Sql("UPDATE MyTableName SET C=CASE
WHEN A = 0 THEN 0
WHEN B = 1 THEN 1
...
ELSE 0
END WHERE ...);
}
use whatever condition you need in migrationBuilder

Mahdi
- 150
- 1
- 8