July 7, 2014

I am using Entity Framework to insert data to a database and I am getting the exception below.

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at MethodName(Int32 id, ...) in c:\Users\project\filename.cs:line 33}
  


It's not obvious what the issue is from the above message and to identify the issue I need to the following code in the catch section of the try catch block.

Code Snippet
  1. try
  2. {
  3.     en.SaveChanges();
  4. }
  5.  
  6. catch (System.Data.Entity.Validation.DbEntityValidationException ex)
  7. {
  8.     foreach (var errors in ex.EntityValidationErrors)
  9.     {
  10.         foreach (var validationError in errors.ValidationErrors)
  11.         {
  12.               string error =  validationError.PropertyName + " ; "+validationError.ErrorMessage;
  13.         }
  14.     }
  15. }
  16.  
  17. catch (Exception ex)
  18. {
  19.  
  20. }


With this line of code, I inserted breakpoint so I could see what the error is. It turned out that it was inserting string data with a much higher length than allowed in the database. So, I updated the database column and added the size which fixed the issue.

0 comments:

Reference: Shahed Kazi at AspNetify.com