Exemplo n.º 1
0
        public static TValidationMetadata GetValidationOrCreateNew <TValidationMetadata>([NotNull] this ModelMetadataItem item)
            where TValidationMetadata : class, IModelValidationMetadata, new()
        {
            var validation = item.GetValidation <TValidationMetadata>();

            if (validation == null)
            {
                validation = new TValidationMetadata();
                item.Validations.Add(validation);
            }

            return(validation);
        }
        private static void SyncValidations([NotNull] ModelMetadataItem metadataFrom, [NotNull] ModelMetadataItem metadataTo)
        {
            if (metadataFrom.Validations.Count > 0)
            {
                var types = new HashSet <Type>();
                foreach (var metadata in metadataTo.Validations)
                {
                    var type = metadata.GetType();
                    if (!types.Contains(type))
                    {
                        types.Add(type);
                    }
                }

                //TODO: how about Deleged validation? just rewrite it completely?

                foreach (var validation in metadataFrom.Validations)
                {
                    if (!types.Contains(validation.GetType()))
                    {
                        metadataTo.Validations.Add(validation);
                    }
                }
            }

            if (metadataTo.IsRequired == null && metadataFrom.IsRequired.HasValue && metadataFrom.IsRequired.Value)
            {
                metadataTo.IsRequired = metadataFrom.IsRequired.Value;
            }

            // ensure that Required attribute is removed
            if (metadataFrom.IsRequired.HasValue && !metadataFrom.IsRequired.Value)
            {
                var requiredValidation = metadataTo.GetValidation <RequiredValidationMetadata>();
                if (requiredValidation != null)
                {
                    metadataTo.Validations.Remove(requiredValidation);
                }
                metadataTo.IsRequired = false;
            }
        }