I think adding try/catch for every SaveChanges()
operation is not a good practice, it's better to centralize this :
Add this class to the main DbContext
class :
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
throw new DbEntityValidationException(errorMessages);
}
}
This will overwrite your context's SaveChanges()
method and you'll get a comma separated list containing all the entity validation errors.
this also can improved, to log errors in production env, instead of just throwing an error.
hope this is helpful.