UPD
Solution here.
验证前需要手动注册元数据类
===================
我想这个问题与 EF 为您的实体生成的代理类有关。您可以在运行时轻松检查:只需查看 GetType().FullName。
如果属性被标记为不可继承,则不会在继承类中应用。并且代理类派生自实体类,所以不可继承的属性会丢失。
我正在尝试通过手动检查属性在 WebForms 项目中使用 DataAnnotations。但两者都没有
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, new ValidationContext(value, null, null), results, true);
也没有
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());
不起作用。
我已经使用与 EF 无关的简单类尝试了这些代码,并且所有 DataAnnotations 属性都已找到并正确检查。
[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 的定义是
[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = false)]
public class RequiredAttribute : ValidationAttribute
默认情况下它成为可继承属性。我不知道为什么
Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true)
// true specifies to also search the ancestors of element for custom attributes.
没有抓到。
欢迎提出任何想法。