I have a try catch for exception when saving changes to a EntityFramework database.
Exception occurs due to a property not having the correct number of characters.
in the catch statement i check for the type of Exception (dbEntityValidationException) and log the error message.
Now when i debug the problem, there are two EntityValidationErrors attached to the exception. But both of these are for the same error (property must be a string or array with a minimum of 9 characters).
Why would there be two errors for the same thing on one exception? I could understand if was talking about different properties, or different errors, but this is same property two of the same error. I'm using this to debug the issue as to why its failing the validation, as when i check the string it is 9characters long (i've used.Trim() to make sure no whitespace).
Below is a condensed version of my code.
code:
[Display(Name = "number")]
[Required]
[StringLength(9,MinimumLength=9)]
public string Number{ get; set; }
string num = "NHG443ER2";
db.SaveChanges()
catch (DbEntityValidationException ex)
{
foreach (var failure in ex.EntityValidationErrors)
{
string validationErrors = "";
foreach (var error in failure.ValidationErrors)
{
validationErrors = myErrorOutput;
using(StreamWriter writer = new StreamWriter(HostingEnvironment.ApplicationPhysicalPath + "\\MigrationErrors.txt",true))
{
writer.WriteLine(validationErrors);
}
}
}
}