Sometimes, we see following error message while working with Entity Framework in ASP.NET MVC.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
To get error messages from EntityValidationErrors
, we can loop through them that is nothing but collection of DbEntityValidationResult
and then each DbEntityValidationResult
object has ValidationErrors
property that actually gives the error message.
public ActionResult ReceiveParameters(PersonalDetails pd)
{
try
{
db.PersonalDetails.Add(pd);
db.SaveChanges();
}
catch (DbEntityValidationException ee)
{
foreach (var error in ee.EntityValidationErrors)
{
foreach(var thisError in error.ValidationErrors)
{
var errorMessage = thisError.ErrorMessage;
}
}
}
return View();
}
Notice in the above code snippet, when an error occurs in the try block, it throws DbEntityValidationException
error because all the code that is written in the try block is Entity Framework code. We are getting the EntityValidationErrors
property of the error object (ee) and interating through each DbEntityValidationResult
(error in first foreach loop) that in iterm gives collection of DbValidationError
collection. Each DbValidationError
object (thisError) has ErrorMessage
property that shows the actual error occured.