简体   繁体   中英

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 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?

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM