Today I encountered the following error during data insertion with Entity Framework as per the Title shown.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

There could be various causes of such an issue. Here I am talking about one of them. In the database I restricted the Name column data Type to nvarchar(10) and I was inserting the value that has more than 10 characters.



As soon as I try to insert a value it generates an error as depicted below:



I have used the code as shown below to identify the root cause.

  1. public ActionResult Create(EmpRegistration collection)
  2. {
  3. try
  4. {
  5. }
  6. catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
  7. {
  8. Exception raise = dbEx;
  9. foreach (var validationErrors in dbEx.EntityValidationErrors)
  10. {
  11. foreach (var validationError in validationErrors.ValidationErrors)
  12. {
  13. string message = string.Format("{0}:{1}",
  14. validationErrors.Entry.Entity.ToString(),
  15. validationError.ErrorMessage);
  16. // raise a new exception nesting
  17. // the current instance as InnerException
  18. raise = new InvalidOperationException(message, raise);
  19. }
  20. }
  21. throw raise;
  22. }
  23. }

This code helps you to trace the exact error. The way it suggested to me was that “The field Name must be a string or array type with a maximum length of '10'.”



This is the complete code that runs perfectly as.I wish this code will help you sometime.

  1. public ActionResult Create(EmpRegistration collection)
  2. {
  3. try
  4. {
  5. if (ModelState.IsValid)
  6. {
  7. EmpRegistration empRegis = new EmpRegistration();
  8. // TODO: Add insert logic here
  9. empRegis.Address = collection.Address;
  10. empRegis.City = collection.City;
  11. empRegis.Id = 7;
  12. empRegis.Name = collection.Name;
  13. objEnity.EmpRegistrations.Add(empRegis);
  14. objEnity.SaveChanges();
  15. return View();
  16. }
  17. return View(objEnity.EmpRegistrations);
  18. }
  19. catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
  20. {
  21. Exception raise = dbEx;
  22. foreach (var validationErrors in dbEx.EntityValidationErrors)
  23. {
  24. foreach (var validationError in validationErrors.ValidationErrors)
  25. {
  26. string message = string.Format("{0}:{1}",
  27. validationErrors.Entry.Entity.ToString(),
  28. validationError.ErrorMessage);
  29. // raise a new exception nesting
  30. // the current instance as InnerException
  31. raise = new InvalidOperationException(message, raise);
  32. }
  33. }
  34. throw raise;
  35. }
  36. }

To learn more about MVC please go through the following link.

MVC Articles

Enjoy coding and reading.