When is a DbEntityValidationException exception raised? One example from real life
Posted: (EET/GMT+2)
I was today working on an ASP.NET web application that uses Entity Framework 6.0 for data access in an SQL Server database. I had implemented a data integration solution, but suddenly, I noticed that one method I had implemented started throwing a DbEntityValidationException exception. This exception class is defined in the System.Data.Entity.Validation namespace.
This is what the MSDN documentation says about this exception type:
Represents an exception thrown from SaveChanges when the validation of entities fails.
This exception type is pretty complex, and contains information about data validation errors. Shortly put, the entity model's data is validated before it is sent to the database.
However, the problem with this exception is that getting the real exception information at runtime forces you to write extra code to manipulate this particular exception type. This is not hard, but still manual work.
In my case, the reason for the exception at runtime was a mismatch between the model and the actual database schema. In my model, a certain string field had the maximum length of 100, but in the database, this limit had been increased to 500.
When I queried a single row from the database using LINQ, modified one field, and tried to save the changes back, this exception was thrown. The remedy was to update the Entity model (EDMX file) so that the MaxLength property matches the actual size of the field in the database.
The lesson is to keep your model updated regularly. Sometimes, clients forget to mention that they've made changes to the database schema, and as a developer, it's your role to adjust.
Hope this helps!