簡體   English   中英

如何在 c# 中的現有數據表中添加新列

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

我已經為“訂單”實體創建了數據表。 現在我想為該現有表添加一個新列。 要添加的新屬性是 boolean 值,默認情況下必須為“false”。 有沒有辦法做到這一點? 這是現有的數據表。 (我已經刪除了表中的所有數據,這就是它們保持為空的原因。)

這是 model。 (應該添加的屬性正如我在代碼中注釋的那樣。我不知道我做的方式是對還是錯。但它不起作用。我添加了代碼但它沒有添加一列數據表。)

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; } 
    }
}

請問有專家可以幫我解決這個問題嗎?

您不需要添加 [DefaultValue(false)],只需 public bool Complete 就足夠了。

首先,添加一個新的遷移:

Add-Migration initxxxxx(new name)

然后將顯示一個新的遷移文件,其中包含以下代碼:

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

可以看到 defaultValue 是默認設置的。 但是如果你想將 defaultValue 更改為 true,你應該將AddColumn更改為AlterColumn並更改 defaultvalue,否則更改將不會被應用。

最后使用Update-Database並刷新您的數據庫以檢查結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM