Many thanks to Jeremy Grunwald for the answer above ... I am completely stuck on this.
I wanted to create a standard validation class based on this solution, but I did not want to go through the metadata class class because it just felt ugly.
To do this, I created a static class that searches for user attributes to get the type of the metadata class, and then registers this class before returning the validation results.
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; namespace MyApp.Validation { public static class EntityValidator { public static List<ValidationResult> Validate(object instance, bool validateAllProperties = true) { RegisterMetadataClass(instance); var validationContext = new ValidationContext(instance, null, null); var validationResults = new List<ValidationResult>(); Validator.TryValidateObject(instance, validationContext, validationResults, validateAllProperties); return validationResults; } private static void RegisterMetadataClass(object instance) { var modelType = instance.GetType(); var metadataType = GetMetadataType(modelType); if (metadataType != null) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(modelType, metadataType), modelType); } } private static Type GetMetadataType(Type type) { var attribute = (MetadataTypeAttribute)type.GetCustomAttributes(typeof (MetadataTypeAttribute), true).FirstOrDefault(); return attribute == null ? null : attribute.MetadataClassType; } } }
use is simple as:
var errors = EntityValidator.Validate(myEntity);
Kevin owen
source share