【问题标题】:When Adding Data Annotation Attribute it's throwing Exception添加数据注释属性时抛出异常
【发布时间】:2014-10-26 04:45:04
【问题描述】:
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; }
}  

当我将数据注释[Required(ErrorMessage = "Employee Name is required")] 添加到Name 属性时,它会抛出InvalidOperationException。当我试图修复错误时,我在网上收到了这些建议:

这意味着您在EmployeeContext 中使用的类之一已更改,但数据库尚未更新,因此现在已过时。您需要更新此使用 Code First 迁移。

当我进行以下更改时,它现在会抛出错误

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. 添加数据注释属性时抛出异常,为什么数据库表列没有变化?

现在沉迷于您的教程

【问题讨论】:

    标签: sql-server asp.net-mvc data-annotations dbcontext invalidoperationexception


    【解决方案1】:
    1. 用户Migration更新数据库结构
    2. 如果没有 [Required] 字段,名称允许为 null (varchar(x) null),而 [Required] 名称更改不为 null (varchar(x) not null)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多