The entity framework gives me generic messages in the exception without telling me the exact entity and the attribute which caused the error. How do I get more information about
Here's the code I have in my solution:
try
{
_context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
//raise a new exception inserting the current one as the InnerException
raise = new InvalidOperationException(message , raise);
}
}
throw raise;
}
You can use it as a basis to add into your solution ... it builds a nested set of exceptions with all the details from Entity Framework.
You need to write tests for repositories and in the base class for your tests:
try
{
DbContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
throw;
}