添加数据注释属性时会引发异常

添加数据注释属性时会引发异常

问题描述:

public class Employee {

    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string Address { get; set; }
    public decimal Salary { get; set; }
    public string Email { get; set; }
}

public class EmployeeContext : DbContext
{
   public DbSet<Employee> Employees { get; set; }
}  

当我向Name属性添加数据注释[Required(ErrorMessage = "Employee Name is required")]时,它会抛出InvalidOperationException.当我尝试修复该错误时,我正在网上获得这些建议:

When I'm adding Data Annotation [Required(ErrorMessage = "Employee Name is required")] to the Name property it's throwing an InvalidOperationException. As I was trying to fix the bug I'm getting these suggestions online:

这意味着您在EmployeeContext中使用的一个类已更改,但是数据库尚未更新,因此现在已过期.您需要更新此使用代码优先迁移.

It means one of your classes use in the EmployeeContext has changed, but the database hasn't been updated so is now out of date. You need to update this use Code First migrations.

当我进行以下更改时,现在会引发错误

When I'm making the following changes its throwing an error now

public class Employee {

    [Key]
    public int Id { get; set; }

    [DisplayName("Employee Name")]
    [Required(ErrorMessage = "Employee Name is required")]

    [StringLength(35)]
    public string Name { get; set; }

    public string Address { get; set; }
    public decimal Salary { get; set; }
    public string Email { get; set; }
}

快照:

问题:

  1. 如果创建了数据库表,是否可以更改列?
  2. 添加数据注释属性时会引发异常,为什么数据库表列未更改?

现在就沉迷于您的教程

  1. 用户迁移以更新数据库结构
  2. 没有[Required]字段名称允许为null(varchar(x)为null),而[Required]名称更改为非null(varchar(x)不为null)
  1. User Migration for update database structure
  2. Without [Required] filed Name allow null (varchar(x) null), with [Required] Name change not null (varchar(x) not null)

如果数据库中有名称可为空的行,则更新时可能会出错(带有迁移)

If in database threre are rows with nullable Name, can be error on update (with migration)