Monday, July 29, 2013

DbEntityValidationException - Entity framework validation error handling

A sample code to catch part of an error handling when dealing with Entity Framework.
try { ... } catch (DbEntityValidationException dbEx) { #region LINQ query to get EF DB entity validation errors /* var errMsgs = dbEx.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage).ToArray(); var exceptionFullErrMsg = string.Concat( dbEx.Message, " Validation errors (DbEntityValidationException): " + UtilityHelper.ErrMsgBuilder(errMsgs)); log.Error(exceptionFullErrMsg); */ #endregion #region Loop to find Entity Framework DB entity validation errors foreach (var validationErrors in dbEx.EntityValidationErrors) foreach (var validationError in validationErrors.ValidationErrors) log.Error(UtilityHelper.ErrMsgBuilder(new string[] { "DbEntityValidationException" , validationError.ErrorMessage } )); #endregion } catch (Exception ex) { #region Exception logging log.Error(UtilityHelper.ErrMsgBuilder( new string[] { ex.GetType().Name } ), ex); #endregion } finally { ... } ... #region Utility Helper class public class UtilityHelper { public static string ErrMsgBuilder(String[] msgArray) { StringBuilder sbErr = new StringBuilder(); foreach (string msg in msgArray) sbErr.AppendLine(msg); return sbErr.ToString(); } } #endregion

Share/Bookmark

No comments: