问题
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:
- If a Database Table is created is it possible to change a column ?
- 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:
- User Migration for update database structure
- 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