Home > Blockchain >  Add new column in database by migration c#
Add new column in database by migration c#

Time:07-03

I have a table, 2 column named A and B. A has value 1 or 0. I want to add new column C, has default value is 0 and C'values depend on A'value. How can I do that? My project is related to migration, C#, ASP.NET Core. Sorry if my description is too bad, I am just a newbie. Thanks for your helps!

CodePudding user response:

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

CodePudding user response:

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

  • Related