当我使用 Validator.TryValidateObject 时验证不起作用

发布于 2024-08-24 06:50:21 字数 684 浏览 4 评论 0原文

DataAnnotations 不适用于伙伴类。以下代码始终验证 true。为什么 ?

var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);

这是好友类。

public partial class Customer 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
}

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer 
{ 
    public class CustomerMetaData 
    { 
        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name { get; set; } 
    } 
}

这是另一个有同样问题的帖子,但没有答案。 链接文本

DataAnnotations does not work with buddy class. The following code always validate true. Why ?

var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);

and here is the buddy class.

public partial class Customer 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
}

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer 
{ 
    public class CustomerMetaData 
    { 
        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name { get; set; } 
    } 
}

Here is another thread with same question., but no answer.
link text

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

时光病人 2024-08-31 06:50:21

我在这里找到了答案: http://forums.silverlight.net/forums/p /149264/377212.aspx

MVC 识别 MetaDataType 属性,但其他项目不识别。在验证之前,需要手动注册元数据类:

TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetadata)), typeof(Customer));

var isValid = Validator.TryValidateObject(new Customer(), context, results, true);

I found the answer here: http://forums.silverlight.net/forums/p/149264/377212.aspx

MVC recognizes the MetaDataType attribute, but other projects do not. Before validating, you need to manually register the metadata class:

TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetadata)), typeof(Customer));

var isValid = Validator.TryValidateObject(new Customer(), context, results, true);
空名 2024-08-31 06:50:21

经过一番研究,我找不到任何原因,如果我使用 MetadataType (伙伴类),TryValidateObject 总是返回 true。但它适用于以下代码(xVal)。

    public static IEnumerable<ErrorInfo> GetErrors(object instance, string name)
    {
        var metadataAttrib = instance.GetType()
                .GetCustomAttributes(typeof(MetadataTypeAttribute), true)
                .OfType<MetadataTypeAttribute>().FirstOrDefault();
        var buddyClassOrModelClass = metadataAttrib != null
                ? metadataAttrib.MetadataClassType
                : instance.GetType();
        var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass)
            .Cast<PropertyDescriptor>();
        var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType())
            .Cast<PropertyDescriptor>();

        var list = from buddyProp in buddyClassProperties
                   join modelProp in modelClassProperties on
                            buddyProp.Name equals modelProp.Name
                   from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(modelProp.GetValue(instance))
                   select new ErrorInfo(
                       buddyProp.Name,
                       attribute.FormatErrorMessage(modelProp.Name),
                       instance);

        if (name != null)
            list = list.Where(x => x.PropertyName == name);

        return list;
    }

After some research I couldn't find any reason why TryValidateObject always return true if I use MetadataType (buddy class). But it works with the following code (xVal).

    public static IEnumerable<ErrorInfo> GetErrors(object instance, string name)
    {
        var metadataAttrib = instance.GetType()
                .GetCustomAttributes(typeof(MetadataTypeAttribute), true)
                .OfType<MetadataTypeAttribute>().FirstOrDefault();
        var buddyClassOrModelClass = metadataAttrib != null
                ? metadataAttrib.MetadataClassType
                : instance.GetType();
        var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass)
            .Cast<PropertyDescriptor>();
        var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType())
            .Cast<PropertyDescriptor>();

        var list = from buddyProp in buddyClassProperties
                   join modelProp in modelClassProperties on
                            buddyProp.Name equals modelProp.Name
                   from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(modelProp.GetValue(instance))
                   select new ErrorInfo(
                       buddyProp.Name,
                       attribute.FormatErrorMessage(modelProp.Name),
                       instance);

        if (name != null)
            list = list.Where(x => x.PropertyName == name);

        return list;
    }
贩梦商人 2024-08-31 06:50:21

虽然我没有在 .NET 4.0 中测试您的代码,但在 .NET 3.5 / Silverlight 3 中,您的元数据类应该如下所示:

[MetadataType(typeof(Customer.CustomerMetaData))]
public partial class Customer 
{ 
    internal sealed class CustomerMetaData 
    {
        private CustomerMetaData()
        {
        }

        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name; 
    } 
}

Although I did not test your code in .NET 4.0, in .NET 3.5 / Silverlight 3, your metadata class should look like this:

[MetadataType(typeof(Customer.CustomerMetaData))]
public partial class Customer 
{ 
    internal sealed class CustomerMetaData 
    {
        private CustomerMetaData()
        {
        }

        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name; 
    } 
}
余生一个溪 2024-08-31 06:50:21

存在一个问题:对象上下文无法识别 MetadataType 属性。虽然您可以在验证之前手动添加类型描述符:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetaData)), typeof(Customer));

更简洁的处理方法是更新实体模型 .tt 文件,将以下内容添加到每个 DTO:

    Type currentType = MethodBase.GetCurrentMethod().DeclaringType;
    object[] attributes = currentType.GetCustomAttributes(typeof(MetadataTypeAttribute),false);
    if(attributes.Length > 0)
    {
        //MetadataType attribute found!
        MetadataTypeAttribute metaDataAttribute = (MetadataTypeAttribute)attributes[0];
        TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(
                currentType, metaDataAttribute.MetadataClassType),currentType);
    }

这将允许您将属性添加到部分类中:

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{

}

public partial class CustomerMetaData
{
    [Required]
    public string CustomerName { get; set; }
}

There is an issue where the MetadataType attribute is not being recognized by the object context. While you can manually add the type descriptor before validation:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetaData)), typeof(Customer));

a more concise way to handle it would be to update the Entity Model .tt file, to add the following to each DTO:

    Type currentType = MethodBase.GetCurrentMethod().DeclaringType;
    object[] attributes = currentType.GetCustomAttributes(typeof(MetadataTypeAttribute),false);
    if(attributes.Length > 0)
    {
        //MetadataType attribute found!
        MetadataTypeAttribute metaDataAttribute = (MetadataTypeAttribute)attributes[0];
        TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(
                currentType, metaDataAttribute.MetadataClassType),currentType);
    }

This will allow you to add the attributes to the partial classes:

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{

}

public partial class CustomerMetaData
{
    [Required]
    public string CustomerName { get; set; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文