Catch Database Exceptions - DbEntityValidationException - Entity Framework


Catch Database Exceptions - DbEntityValidationException - Entity Framework  (C#,.NET)


When you developing .net application with C#, EntityFramework you may get "Validation failed for one or more entities" error sometimes. With this error you can't find exact error or entity field directly. you may have to do some extra work for that. I am using following simple code for simply find error field.

This is straightforward and very very small code. We can catch our database exseptions Using DbEntityValidationException (Under namespace System.Data.Entity.Validation) in EntityFramework. Im using EntityFramework.6.x. It is also available in EntityFramework 5.x.

In here i am writing my exceptions in to text file in my C: drive (C:\Shared\Error.txt)
Remember you have to give proper permissions for C: drive if you want to write data into text file. I am here i am using this for simplicity and tutorial purpose.

 try  
 {  
  //Your database operations.  
 }  
 catch (DbEntityValidationException e)  
         {  
           string filePath = @"C:\Shared\Error.txt";  
           foreach (var eve in e.EntityValidationErrors)  
           {  
             using (StreamWriter writer = new StreamWriter(filePath, true))  
             {  
               writer.WriteLine("Entity of type \"{0}\" in state \"{1}\" have the following validation errors:",  
               eve.Entry.Entity.GetType().Name, eve.Entry.State);  
               writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);  
               foreach (var ve in eve.ValidationErrors)  
               {  
                 writer.WriteLine("- Property: \"{0}\", Error: \"{1}\"",  
                   ve.PropertyName, ve.ErrorMessage);  
               }  
             }  
           }  
           throw new Exception(e.ToString()); //if you want to debug, otherwise you can remove this line  
         }  


Following sample is the result of the above implimentation.

Error.txt

 Entity of type "STUDENTS" in state "Added" has the following validation errors:  
 -----------------------------------------------------------------------------  
 - Property: "STATUS_REPORT__NAME_1", Error: "The field STATUS_REPORT__NAME_1 must be a string or array type with a maximum length of '50'."  
 - Property: "STATUS_REPORT_NAME_2", Error: "The field STATUS_REPORT__NAME_2 must be a string or array type with a maximum length of '50'."  

Happy coding. Thank you!

Comments

Popular posts from this blog

Create Simple Web API 2 Project in few minutes - .NET Framework - Tutorial NO. 01

ASP.NET Identity With Oracle Database