.net-core - 使用 Entity Framework Core 使用 Code First 迁移自动添加默认列
问题描述
我需要在运行迁移时向模型添加默认列。例如:我在迁移之前创建了一个模型。我正在使用 .net 核心 v3.1
using DataLayer.DataContext;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataLayer.Models
{
[Table("TodoItem", Schema = "dbo")]
public class TodoItem : ModalBase
{
[Required]
[Column(TypeName ="varchar(50)")]
[Display(Name = "Employee Name")]
public string EName { get; set; }
[Required]
[Column(TypeName = "varchar(50)")]
[Display(Name = "Employee Department")]
public string EDept { get; set; }
}
}
现在我希望我的模型在迁移后如下所示。我需要为应用程序中可用的所有模型/实体执行此操作。它应该是自动化的。当我运行迁移时,它应该动态提供默认列。
using DataLayer.DataContext;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataLayer.Models
{
[Table("TodoItem", Schema = "dbo")]
public class TodoItem : ModalBase
{
//default column which has to be added to this model after i run migration
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Column(TypeName ="varchar(50)")]
[Display(Name = "Employee Name")]
public string EName { get; set; }
[Required]
[Column(TypeName = "varchar(50)")]
[Display(Name = "Employee Department")]
public string EDept { get; set; }
//default column which has to be added to this model after i run migration
[Required]
[Column(TypeName = "bit")]
[Display(Name = "IsActive")]
public string IsActive { get; set; }
//default column which has to be added to this model after i run migration
[Required]
[Column(TypeName = "bit")]
[Display(Name = "IsDeleted")]
public string IsDeleted { get; set; }
}
}
需要在数据库表上创建默认列。任何人都可以帮助我提供一个工作示例,将不胜感激。
提前致谢。
解决方案
为此,您只需要在包管理控制台中运行两个命令。1) Add-Migration 命令 2) Update-Database
例如,添加迁移 TodoItem 然后更新数据库
如果要反转迁移,请使用以下命令:Remove-Migration
推荐阅读
- python - cmake 无法识别 environ['PATH'] 中的汉字
- aws-lambda - Aws Lambda - 如何保留有效令牌以用于其他调用
- javascript - 在 insertRow 之后计算表行数
- java - 我如何在java中添加几秒钟的延迟
- xamarin.forms - 如何在 Xamarin iOS 上从 iCloud 获取带有 PHVideo 的视频?
- python - 列表类型的结果转换
- sql - 插入或忽略违反外键约束 sqlite 的行
- php - 使用 php ajax 在数据库中插入和更新不同的表
- python - “权重总和为零,无法标准化”plotly.express 的树形图中的错误
- python - 如何根据输入文件扩展名更改 pd.read_excel() 引擎?