0

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.

2
  • 2
    Read the part about computed columns here. Commented Jul 2, 2022 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 Commented Jul 5, 2022 at 1:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.