You can override the SaveChanges
, to handle this exception and provide better exception details.
You can create a class "next" to your context class... the full code for that class is as follow:
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
namespace MyNamespace
{
public partial class MyContext : DbContext
{
// Override base SaveChanges to expand out validation errors so client gets an actually helpful message
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}
}
Check this for more information: http://devillers.nl/blog/improving-dbentityvalidationexception/