How to handle the DbEntityValidationException in C#

时间:2024-04-13 10:04:07

When I want to use db.SaveChanges(), if some of the columns got validation error and throw DbEntityValidationException, and you can't tell which one is wrong, maybe try this way will help.

You can extract all the information from the DbEntityValidationException with the following code (you need to add the namespaces: System.Data.Entity.Validation and System.Diagnostics to your using list):

try
{
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}

Using debug tools, set breakpoints, then you will see the detail error message during the foreach loop.