Devindi Siwurathna
Devindi Siwurathna

Reputation: 85

how to add a new column to an existing data table in c#

I have created the data table for 'order' entity. Now I want to add a new column for that existing table. The new attribute to be added is a boolean value which must be having 'false' by default. Is there a way to do this? This is the existing data table. (I have deleted all the data in the table that's why they are staying as null.)

This is the model. (The attribute which should be added is as I have commented in the code. I don't know whether the way I have done it right or wrong. But it is not working. I added the code but it does not add a column to the data table.)

using Microsoft.AspNetCore.Http;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;

namespace E_Pharmacy.Models
{
    public class Order
    {
        [Key]
        public int OrderID { get; set; }
        public DateTime DateTime { get; set; }

        public string Status { get; set; }

        //[DefaultValue(false)]
        //public bool Complete { get; set; } //this is the attribute which should be added newly.
        public string Status2 { get; set; }
        public string PharmacyName { get; set; }
        public string CustomerName { get; set; }
        public string PatientName { get; set; }
        public int PatientAge { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public int TeleNo { get; set; }
        public int CustomerId { get; set; }

        
        public string ImageName{ get; set;}

        [NotMapped]
        public IFormFile ImageFile { get; set; }
        [NotMapped]
        public String ImageSrc { get; set; }
        //[ForeignKey("Pharmacy")]
        public int PharmacyId { get; set; }
        //public Pharmacy Pharmacy { get; set; } 
    }
}

Can some expert help me in this matter please?

Upvotes: 0

Views: 1278

Answers (1)

Jerry Cai
Jerry Cai

Reputation: 939

You do not need to add [DefaultValue(false)], just public bool Complete is enough.

First, Add a new Migration:

Add-Migration initxxxxx(new name)

Then a new migration file will show with these code:

migrationBuilder.AddColumn<bool>(
            name: "Complete2",
            table: "Order",
            type: "bit",
            nullable: false,
            defaultValue: false);

You can see that defaultValue is set by default. But if you want to change defaultValue to true, you should change AddColumn to AlterColumn and change the defaultvalue, or the change will not be applied.

Finally use Update-Database and refresh your database to check the result:

enter image description here

Upvotes: 1

Related Questions