All of the applications I put into production use ELMAH to track unhandled exceptions. In one our new releases of an application I noticed a semi-rare bug occurring through these logs.
Validation Failed
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities.
I initially figured something extraordinary occurred for this to happen. Then it happened again and then another time. Now I felt it was time to give this error a more thorough review. Something less then extraordinary was likely happening.
I use data annotations on my database model since I’m using Entity Framework Code First (EF CF) and in my view models. I was a little concerned that some nefarious input was being entered that the client side unobtrusive JavaScript was missing as well as in my server side checks.
As it has almost always turned out when I suspect something like this, the true answer is something much simpler and sometimes even a bit embarrassing.
Here’s the offending view model / with the EF CF model. Can you catch the issue?
//View Model public class MyCourseViewModel { [Display(Prompt = "Yada Yada Yada College")] [Required] public string College{ get; set; } [Display(Name = "Course Title", Prompt = "Intro to Psychology")] [Required] public string Name { get; set; } [Display(Name = "Course Prefix & Number", Prompt = "PSY 101")] [Required] public string CourseNumber{ get; set; }
//…more view model fields…. } //Database Model... public class MyDatabaseModel{ [StringLength(150)] public string College{ get; set; } [Required] [StringLength(150)] public string Name{ get; set; } [Required] [StringLength(25)] public string CourseNumber { get; set; } }
Mismatched Annotations
In my database model I set maximum lengths for my strings but I didn’t for my view model. Enter the case where a user enters a value longer than the allowable amount and you have the client side & server side checks all pass on the view model but then an error occurs at the database model level since you’ve exceeded your length.
Takeaway
Make sure you at least have matched or created a more stringent rule in your view models as you do in your database models. A simple oversight on my part and definitely not intentional.
Logging
Takeaway number two: Log, log, and log. Then be sure to review those logs not just ignore them. Take action when you begin to see a pattern.
Dealing with exceptions
Adding ELMAH to my MVC projects has been a breeze and has offered a great amount of insight into unforeseen bugs. I often don’t react to the first new bug that ELMAH reports. I instead look to see if it’s a pattern and when one emerges I then put it on my list to deal with.
Happy Coding!
PS – I realize a better test setup would have been able to prevent this bug from ever making it into the wild. A unit test would have even missed this but not an integration test. Some extra food for thought on how testing can save your bacon…. Mmm… bacon.