Just spent a couple of hours trying to get to the bottom of this. ![]()
Basically, if you have a generated-code class (like in entity framework), the easiest way to add validation is to use MetadataType in the partial class (because you can’t add attributes to the generates properties – you would lose them if the code gets regenerated).
[MetadataType(typeof(JobMetadata))]
partial class Job : IGuidID
{
public class JobMetadata
{
[Required]
public global::System.String Title { get; set; }
}
...
}
When using ASP.NET MVC’s ModelState.IsValid and the default MVC validation, everything goes as expected – the [Required] attribute is respected and you get the appropriate validation error message.
Now, if you need to run the validation manually, using Validator.[Try]ValidateObject(…), you’re in for a nasty surprise: the validation passes, ignoring your attributes.
After a lot of searching, I finally narrowed it down to MetadataType, got the right search terms and found the answer on Stack Overflow (of course): you need to manually register the MetadataType provider.
static Job()
{
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Job), typeof(JobMetadata)), typeof(Job));
}
Here is the link for the full answer.