Entity Framework Validation failed for one or more entities的解决方法

在使用EneityFramework的SaveChanges(),如果赋值的类型不对,或者没有满足Entity的属性条件,EntityFramework会抛Validation failed for one or more entities的异常,但是这个异常的详细信息里并不直接指出是哪个字段出错了。

解决方法:把SaveChange()包在一个Try里,捕获DbEntityValidationException,打印EntityValidationErrors

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);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *