首页 > 解决方案 > 使用 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; }
    }
}

需要在数据库表上创建默认列。任何人都可以帮助我提供一个工作示例,将不胜感激。

提前致谢。

标签: .net-coreentity-framework-coreazure-functions

解决方案


为此,您只需要在包管理控制台中运行两个命令。1) Add-Migration 命令 2) Update-Database

例如,添加迁移 TodoItem 然后更新数据库

如果要反转迁移,请使用以下命令:Remove-Migration


推荐阅读