An instance of validation failure for one or more entities. For more information, see Resolution of the 'EntityValidationErrors' Property

I believe that as long as you are doing MVC, you have encountered this problem, and you all know the cause of the error, which is to trigger the defined instance field validation rules. For example, the definition is not empty, but it is empty, or the length of the defined field is 50, but it exceeds 50.

 

But sometimes even though you know this is the case, you still have no idea how to solve the specific problem. I recently encountered a problem that I know occurs when updating a certain table. However, this error cannot be realized locally. This error occurs in a specific condition. I don't know what the specific condition is, which is very depressing.

I found it on the Internet, and I know that this error will trigger the DbEntityValidationException exception. This exception will have detailed exception information to explain which field it is and what error has occurred, but it needs to be output in a loop. Intend to output to the log file to see what is wrong. code show as below:

 

[csharp]  view plain copy  
 
  1. try  
  2.                    {  
  3.                        es2.Update(examList);  
  4.                    }  
  5.                    catch (DbEntityValidationException dbEx)  
  6.                    {  
  7.                        foreach (var validationErrors in dbEx.EntityValidationErrors)  
  8.                        {  
  9.                            foreach (var validationError in validationErrors.ValidationErrors)  
  10.                            {  
  11.   
  12.                                EventLog.Log(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName,  
  13.                                    validationError.PropertyName,  
  14.                                    validationError.ErrorMessage), "error");  
  15.                            }  
  16.                        }  
  17.                        throw;  
  18.                    }  
  19.                    catch (Exception ex)  
  20.                    {  
  21.                        throw;  
  22.                    }  

 

The reason for using 2 catches is to prevent no error log when there are other non-DbEntityValidationException errors.

Namespace where DbEntityValidationException is located: System.Data.Entity.Validation

Compile, upload to the server, and after a while, check the log file and find the cause of the error.

 Class: System.Data.Entity.DynamicProxies.ExamList_839A196D8FC4CF7E8A791B7F29782BA535E73532A1C3C2C00FD6EF30B6C4A660, Property: StudentAnswer, Error: The field StudentAnswer must be a string with a maximum length of 50.
The StudentAnswer field is not long enough. It's easy to find the answer. Expand field size, problem solved

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326369230&siteId=291194637