In the event of an error message, "One or more entities failed. View" Entity ValidationError "attributes to learn more details, you can access the verification error group.
Check the verification error
try { // 代码 context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("实体: \"{0}\", 状态: \"{1}\"", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach(var ve in eve.ValidationErrors) { Console.WriteLine("- 属性: \"{0}\", 错误: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; }
Advanced improvement <高>
foreach(var ve in eve.ValidationErrors) { Console.WriteLine("- 属性: \"{0}\", 值: \"{1}\", 错误: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName), ve.ErrorMessage); }
<含> Custom abnormalities containing detailed messages:
Debug.Write("- 属性: \"{0}\", 值: \"{1}\", 错误: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName), ve.ErrorMessage);
<写> Rewilling SaveChanges:
public class FormattedDbEntityValidationException : Exception { public override string Message => InnerException != null ? InnerException?.ToDetailedString() : ""; }
The above is the detailed content of How to Effectively Handle and Debug Entity Validation Errors in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!