Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.
当你遇到这个的时候你会发现,EntityValidationErrors里面没有什么东西({System.Data.Entity.Validation.DbEntityValidationResult}).
并不能让我们知道究竟是什么错误导致无法操作数据库.那么我们如何能知道错误在那呢:
While you are in debug mode within the catch {…} block open up the “QuickWatch” window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
This will allow you to drill down into the ValidationErrors tree. It’s the easiest way I’ve found to get instant insight into these errors.
For Visual 2012+ users who care only about the first error and might not have a catch block, you can even do:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage
For those not referencing System.Linq and using immediate window:
System.Linq.Enumerable.ToList(System.Linq.Enumerable.ToList(((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors)[0].ValidationErrors)[0].ErrorMessage
You could try this in a try/catch block?
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);
}
}
}
The best solution in my opinion, is to handle this kind of errors in a centralized way.
just 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.PropertyName + ": " + x.ErrorMessage));
throw new DbEntityValidationException(errorMessages);
}
}
来自 http://*.com/questions/5345890/getting-exact-error-type-in-from-dbvalidationexception