Wednesday, 2 August 2017

Validation Failed For One or More Entities: MVC/Entity Framework 5.0

Validation Failed For One or More Entities: MVC/Entity Framework 5.0


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.
Then Above Error was Occured.




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 a new exception nesting  
                // the current instance as InnerException  
                raise = new InvalidOperationException(message, raise);  
            }  
        }  
        throw raise;  
    }  
}  



public ActionResult Create(EmpRegistration collection)  
{  
    try  
    {  
        if (ModelState.IsValid)  
        {  
            EmpRegistration empRegis = new EmpRegistration();  
            // TODO: Add insert logic here  
            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 a new exception nesting  
                // the current instance as InnerException  
                raise = new InvalidOperationException(message, raise);  
            }  
        }  
        throw raise;  
    }  
}  

No comments:

Post a Comment

React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...