UPD Solution here.
Before validating, you need to manually register the metadata class
==================
I suppose this problem is related to proxy classes, which EF generates for your entities. You can check this easily in runtime: just see GetType().FullName.
If attribute is marked as non-inheritable, it won't be applied in inherited class. And proxy classes derive from entity classes, so non-inheritable attributes are lost.
I'm trying to use DataAnnotations in WebForms project by checking attributes by hand. But neither
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, new ValidationContext(value, null, null), results, true);
nor
PropertyInfo[] properties = value.GetType() .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var validationProperties = properties.Select(prop => new { Property = prop, ValidationAttributes = Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true) }).Where(valProp => valProp.ValidationAttributes.Any());
doesn't work. I've tried these code with simple class not related to EF, and all DataAnnotations attributes were found and checked correctly.
[MetadataType(typeof(TestValidObject_Metadata))] public class TestValidObject { public string IdName { get; set; } } public class TestValidObject_Metadata { [Required, DisplayName("Id name")] public object IdName { get; set; } }
RequiredAttribute's definition is
[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = false)] public class RequiredAttribute : ValidationAttribute
and by default it becomes inheritable attribute. And I don't know why
Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true) // true specifies to also search the ancestors of element for custom attributes.
doesn't catch it.
Any ideas are welcome.