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.
- public ActionResult Create(EmpRegistration collection)
- {
- try
- {
-
- }
- catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
- {
- Exception raise = dbEx;
- foreach (var validationErrors in dbEx.EntityValidationErrors)
- {
- foreach (var validationError in validationErrors.ValidationErrors)
- {
- string message = string.Format("{0}:{1}",
- validationErrors.Entry.Entity.ToString(),
- validationError.ErrorMessage);
-
-
- raise = new InvalidOperationException(message, raise);
- }
- }
- throw raise;
- }
- }
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.
- public ActionResult Create(EmpRegistration collection)
- {
- try
- {
- if (ModelState.IsValid)
- {
- EmpRegistration empRegis = new EmpRegistration();
-
- empRegis.Address = collection.Address;
- empRegis.City = collection.City;
- empRegis.Id = 7;
- empRegis.Name = collection.Name;
- objEnity.EmpRegistrations.Add(empRegis);
- objEnity.SaveChanges();
-
- return View();
- }
- return View(objEnity.EmpRegistrations);
- }
- catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
- {
- Exception raise = dbEx;
- foreach (var validationErrors in dbEx.EntityValidationErrors)
- {
- foreach (var validationError in validationErrors.ValidationErrors)
- {
- string message = string.Format("{0}:{1}",
- validationErrors.Entry.Entity.ToString(),
- validationError.ErrorMessage);
-
-
- raise = new InvalidOperationException(message, raise);
- }
- }
- throw raise;
- }
- }
To learn more about MVC please go through the following link.
MVC Articles
Enjoy coding and reading.