繁体   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