Entityframework | DbEntityValidationException
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities
Resolved entity framework db entity validation exception.
Code:
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); raise = new InvalidOperationException(message, raise); } } throw raise; }
Another way....
catch (DbEntityValidationException dbEx) { var msg = string.Empty; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } var fail = new Exception(msg, dbEx); throw fail; }
No comments:
Post a Comment