MVC Create Error:EntityValidationErrors
I have this on my Module
Module
Code:
public class Person
{
public int ID { get; set; }
[Required]
[StringLength(30)]
public string First { get; set; }
[Required]
[StringLength(30)]
public string Last { get; set; }
public DateTime BirthDate { get; set; }
}
public class PersonContext : DbContext
{
public DbSet<Person> People { get; set; }
}
and this on Controller
Controller
Code:
// GET: /Person/Create
public ActionResult Create(Person person)
{
db.People.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
Every type I click the Create link, I'm encountering this error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Re: MVC Create Error:EntityValidationErrors
You have validation attributes on the properties of your entity but your code is assuming that those attributes will never be violated. You need to check ModelState.IsValid to see whether the data entered by the user passes validation and only save it if it does. If it doesn't you need to redisplay the Create view with the validation errors so that the user can correct them.