[英]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.要添加的新属性是 boolean 值,默认情况下必须为“false”。 Is there a way to do this?有没有办法做到这一点?
This is the model.这是 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.您不需要添加 [DefaultValue(false)],只需 public bool Complete 就足够了。
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.可以看到 defaultValue 是默认设置的。 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.但是如果你想将 defaultValue 更改为 true,你应该将AddColumn更改为AlterColumn并更改 defaultvalue,否则更改将不会被应用。
Finally use Update-Database and refresh your database to check the result:最后使用Update-Database并刷新您的数据库以检查结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.