Home >Backend Development >C++ >How to Effectively Handle and Debug Entity Validation Errors in Entity Framework?
Detailed interpretation of entity verification errors
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
<code class="language-csharp">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; }</code>EntityValidationErrs attribute contains the entity of verification failure, while ValidationError contains the error list of attribute level.
Advanced improvement
<code class="language-csharp">foreach(var ve in eve.ValidationErrors) { Console.WriteLine("- 属性: \"{0}\", 值: \"{1}\", 错误: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName), ve.ErrorMessage); }</code>
Custom abnormalities containing detailed messages:
<code class="language-csharp">Debug.Write("- 属性: \"{0}\", 值: \"{1}\", 错误: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName), ve.ErrorMessage);</code>This exception is verified by formatting messages:
Rewilling SaveChanges:
<code class="language-csharp">public class FormattedDbEntityValidationException : Exception { public override string Message => InnerException != null ? InnerException?.ToDetailedString() : ""; }</code>This ensures that the verification details will be displayed in an error log (em, elmah).
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!