Constrain the number of child entities in Entity Framework

前端 未结 2 1135
渐次进展
渐次进展 2021-01-26 20:25

Bottom Line Up Front

Is there a succinct way that I can constrain the number of child entities that can belong to a parent in Entity Framework. I am using 4.3.1 at th

2条回答
  •  情书的邮戳
    2021-01-26 21:32

    I ended up going with CustomValidationAttribute, and implemented it with a great deal of success. See below for my implementation info:

    In the SearchList entity

        [NotMapped]
        public String ValidationMessage { get; set; }
        [CustomValidation(typeof(EntityValidation.EntityValidators), "ValidateSearchCount")]
        public virtual List Searches { get; set; }
    
        public static bool Create(ProjectContext db, SearchList searchList)
        {
            try
            {
                db.SearchLists.Add(searchList);
                db.SaveChanges();
                return true;
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        searchList.ValidationMessage += validationError.ErrorMessage;
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
    

    EntityValidators Class

        public static ValidationResult ValidateSearchCount(List Searches)
        {
            bool isValid;
            int count = Searches.Count();
            isValid = (count <= 5000 ? true : false);
    
            if (isValid)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult("A maximum of 5000 searches may be added to a SearchList.");
            }
        }
    

    A similar exception block is on the update method. In this way, when SaveChanges gets called it attempts to validate the entity and its child collections, and when the collection count is greater than 5000 the validator will return an error message which gets caught in the exception handler and stored in a local property for my controller to check when things go wrong.

提交回复
热议问题