UPD Solution here.
验证之前,您需要手动注册元数据类
============ ======
我想这个问题与代理类有关,EF为你的entiti生成ES。您可以在运行时轻松检查:请参阅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.
没有捕获它。
欢迎任何想法。
你是如何检查的? – archil 2011-04-08 07:32:19
我试图插入填充数据,并插入一个空值。 – Mukesh 2011-04-08 07:46:18
你是如何通过ASP.Net mvc或简单赋值创建数据的? – archil 2011-04-08 08:17:30