When Adding Data Annotation Attribute it's throwing Exception

╄→尐↘猪︶ㄣ 提交于 2019-12-24 05:24:10

问题


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; }
}  

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:

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; }
}

Snapshot:

Questions:

  1. If a Database Table is created is it possible to change a column ?
  2. When adding a Data Annotation Attribute it's throwing an Exception, why is the database table column not changing ?

Addicted to your tutorials now


回答1:


  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)



来源:https://stackoverflow.com/questions/26518118/when-adding-data-annotation-attribute-its-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!