Example #1
0
        public void CustomValidate(CFAPContext ctx)
        {
            List <DbEntityValidationResult> validationResults = new List <DbEntityValidationResult>();

            var rateResult = ctx.Entry(this).GetValidationResult();

            if (!rateResult.IsValid)
            {
                validationResults.Add(rateResult);
            }

            if (this.DateRate == default(DateTime))
            {
                DbValidationError        validationError          = new DbValidationError(typeof(DateTime).ToString(), "Значениие не определено");
                DbEntityValidationResult dbEntityValidationResult = new DbEntityValidationResult(ctx.Entry(this), new DbValidationError[] { validationError });
                validationResults.Add(dbEntityValidationResult);
            }

            if (validationResults.Count > 0)
            {
                throw new DbEntityValidationException(
                          "Ошибка при проверке данных. Данные могут остутствовать или указаны не верно. Проверте внесенные данные и повторите попытку"
                          , validationResults);
            }
        }
Example #2
0
        /// <summary>
        /// 获取详细验证错误
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static Dictionary <string, string> GetDetailErrorString(DbEntityValidationException dbex)
        {
            try
            {
                //没有验证错误
                if (dbex.EntityValidationErrors.Count() < 1)
                {
                    return(new Dictionary <string, string>());
                }
                //验证错误集合
                Dictionary <string, string> dics = new Dictionary <string, string>();

                foreach (var item in dbex.EntityValidationErrors)
                {
                    //错误信息
                    DbValidationError error = item.ValidationErrors.FirstOrDefault();
                    dics.Add(error.PropertyName, error.ErrorMessage);
                }
                return(dics);
            }
            catch (Exception ex)
            {
                Dictionary <string, string> errorMsg = new Dictionary <string, string>();
                errorMsg.Add("获取错误信息出错", ex.Message);
                return(errorMsg);
            }
        }
            private static string GetDbEntityValidationExceptionMessage(DbEntityValidationException ex)
            {
                StringBuilder builder = new StringBuilder();
                ICollection <DbEntityValidationResult> validationResults = ex.EntityValidationErrors.ToList();

                for (int i = 0; i < validationResults.Count; i++)
                {
                    DbEntityValidationResult        result           = validationResults.ElementAt(i);
                    ICollection <DbValidationError> validationErrors = result.ValidationErrors;
                    for (int j = 0; j < validationErrors.Count; j++)
                    {
                        DbValidationError error = validationErrors.ElementAt(j);
                        builder.Append(error.ErrorMessage);
                        if (j != validationErrors.Count - 1)
                        {
                            builder.Append("; ");
                        }
                    }
                    if (i != validationResults.Count - 1)
                    {
                        builder.AppendLine();
                    }
                }
                return(builder.ToString());
            }
Example #4
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception is DbEntityValidationException)
            {
                DbEntityValidationException dbException
                    = (DbEntityValidationException)actionExecutedContext.Exception;
                DbEntityValidationResult dbValidationResult
                    = dbException.EntityValidationErrors.FirstOrDefault();
                DbValidationError dbFirstValidationError
                    = dbValidationResult.ValidationErrors.FirstOrDefault();

                string responseText
                    = string.Format(
                          CultureInfo.CurrentCulture,
                          "{0}:{1}",
                          dbFirstValidationError.PropertyName,
                          dbFirstValidationError.ErrorMessage
                          );

                actionExecutedContext.Response
                    = new HttpResponseMessage(HttpStatusCode.BadRequest);
                actionExecutedContext.Response.Content
                    = new StringContent(responseText);
            }
        }
Example #5
0
 public static HidErrorInfo FromEFError(DbValidationError error)
 {
     return(new HidErrorInfo()
     {
         Descripcion = string.Format("{1} --> {0}", error.ErrorMessage, error.PropertyName),
         Tipo = ErrorType.Validation
     });
 }
        private object AsError(DbEntityValidationResult dbError, DbValidationError dbErrorEntry)
        {
            var status = "422";
            var detail = dbErrorEntry.ErrorMessage;
            var source = new { pointer = "/data/attributes/" + dbErrorEntry.PropertyName };

            return(new { status = status, detail = detail, source = source });
        }
 private static string GetExceptionMessage(
     DbEntityValidationResult entityValidationError,
     DbValidationError databaseValidationError)
 {
     return(string.Format(
                ErrorEntityValidation,
                entityValidationError.Entry.Entity.GetType().Name,
                entityValidationError.Entry.State,
                databaseValidationError.PropertyName,
                databaseValidationError.ErrorMessage));
 }
Example #8
0
        public static List <Tuple <string, string> > ExtractValidationErrors(DbContext dbContext)
        {
            List <Tuple <string, string> > rtnList = new List <Tuple <string, string> >();

            foreach (DbEntityValidationResult err in dbContext.GetValidationErrors())
            {
                DbValidationError dbError = err.ValidationErrors.ToList()[0];
                rtnList.Add(new Tuple <string, string>(dbError.PropertyName, dbError.ErrorMessage));
            }
            return(rtnList);
        }
Example #9
0
        public void DbValidationError_LogMessage(string propriete, string message)
        {
            var error = new DbValidationError(propriete, message);

            var log = error.LogMessage();

            Assert.NotNull(log);

            Assert.NotEqual(0, log.Length);

            Assert.Contains(propriete, log);

            Assert.Contains(message, log);
        }
        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary <object, object> items)
        {
            if (entityEntry.Entity is User && entityEntry.State == EntityState.Deleted)
            {
                User entity = entityEntry.Entity as User;

                if (entity.IsActive)
                {
                    DbValidationError error = new DbValidationError("IsActive", "Could not be deleted People in Active state");
                    return(new DbEntityValidationResult(entityEntry, new DbValidationError[] { error }));
                }
            }

            return(base.ValidateEntity(entityEntry, items));
        }
Example #11
0
        /// <summary>
        /// Overrides User validation.
        /// </summary>
        /// <param name="entityEntry">User entity</param>
        /// <param name="items">Items</param>
        /// <returns>User validation result</returns>
        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary <object, object> items)
        {
            var result    = base.ValidateEntity(entityEntry, items);
            var userEntry = entityEntry.Entity as User;

            // Check email uniqueness
            if (Users.Where(x => x.EMail == userEntry.EMail && x.Id != userEntry.Id).FirstOrDefault() != default(User))
            {
                var eMailValidationError = new DbValidationError(nameof(User.EMail), "The EMail is not unique");
                result.ValidationErrors.Add(eMailValidationError);
                return(new DbEntityValidationResult(entityEntry, result.ValidationErrors));
            }
            else
            {
                return(result);
            }
        }
Example #12
0
        private void CustomProperiesValidate <TProperty>(TProperty property, CFAPContext ctx, List <DbEntityValidationResult> validationResults) where TProperty : class
        {
            if (validationResults == null)
            {
                throw new ArgumentNullException("List<DbEntityValidationResult> validationResults педреан с неопределенным значением.");
            }

            if (property == null)
            {
                DbValidationError        validationError          = new DbValidationError(typeof(TProperty).ToString(), "Значениие не определено");
                DbEntityValidationResult dbEntityValidationResult = new DbEntityValidationResult(ctx.Entry(this), new DbValidationError[] { validationError });
                validationResults.Add(dbEntityValidationResult);
                return;
            }

            var propertyValidationResult = ctx.Entry(property).GetValidationResult();

            if (!propertyValidationResult.IsValid)
            {
                validationResults.Add(propertyValidationResult);
            }
        }
Example #13
0
 private static string PopulateEFerror(DbValidationError validationError)
 {
     return(string.Format("Property: {0} Error: {1}",
                          validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine);
 }
Example #14
0
        //
        // Summary:
        //     Validation error. Can be either entity or property level validation error.

        //
        // Summary:
        //     Creates an instance of System.Data.Entity.Validation.DbValidationError.
        //
        // Parameters:
        //   propertyName:
        //     Name of the invalid property. Can be null.
        //
        //   errorMessage:
        //     Validation error message. Can be null.
        public DbValidationErrorBase(string propertyName, string errorMessage)
        {
            _dbValidationError = new DbValidationError(propertyName, errorMessage);
        }
 /// <summary>
 /// Returns a formatted message of the validation error.
 /// </summary>
 /// <param name="err">Validation error</param>
 /// <returns>Formatted message</returns>
 public static string LogMessage(this DbValidationError err)
 {
     return(string.Format("[{0} - {1}]", err.PropertyName, err.ErrorMessage));
 }
Example #16
0
        private static void AddErrorInData(this DbEntityValidationException exception, int index, DbValidationError error)
        {
            var key = $"EntityValidationError{index}";

            if (!exception.Data.Contains(key))
            {
                exception.Data[key] = $"Property : {error.PropertyName}, Error : {error.ErrorMessage}";
            }
        }
Example #17
0
        /// <summary>
        /// 修正由于从集合中删除元素而导致外键为空异常
        /// </summary>
        /// <param name="entityEntry"></param>
        /// <param name="result"></param>
        /// <param name="err"></param>
        private void CoerceRemoveFromCollectionError(DbEntityEntry entityEntry, DbEntityValidationResult result, DbValidationError err)
        {
            var errProp = err.PropertyName;

            if (entityEntry.State == EntityState.Modified && entityEntry.Property(errProp).CurrentValue == null)
            {
                bool isEntityRequiredForeignKeyEmpty = IsEntityRequiredForeignKeyEmpty(entityEntry, errProp);
                if (isEntityRequiredForeignKeyEmpty)
                {
                    entityEntry.State = EntityState.Deleted;
                    result.ValidationErrors.Remove(err);
                }
            }
        }
 private static string GetErrorMessage(DbValidationError ee)
 {
     return(string.Join("\n", ee.ErrorMessage));
 }