简体   繁体   English

基于数据注释的验证不适用于导航属性

[英]Data-annotation based validation does not work for navigation properties

I have following classes in my program: 我的程序中有以下课程:

class Container
{
    public Container()
    {
        Contain = new Contain();
    }  

    public Contain Contain { get; set; }
}
class Contain
{
    [Required]
    public string Code { get; set; }
}

As you see I decorated the Code property with [Required] data annotation attribute. 如您所见,我用[Required]数据注释属性修饰了Code属性。 I wrote a Validate method to validate my objects, too: 我也写了一个Validate方法来验证我的对象:

class Program
{
    static bool Validate(object command)
    {
        var validationContext = new ValidationContext(command, null, null);
        var validationMessages = new Collection<ValidationResult>();
        var result =  Validator.TryValidateObject(command, validationContext, validationMessages, true);
        Console.WriteLine("********** " + command.GetType().Name +" **************");

        foreach (var validationMessage in validationMessages)
        {
            Console.WriteLine(validationMessage);
        }
        return result;
    }

    static void Main(string[] args)
    {
        var contain = new Contain();
        Console.WriteLine(Validate(contain));

        var container = new Container();
        Console.WriteLine(Validate(container));
        Console.ReadKey();
    }
}

When I run the program the Validate method returns true for container object and returns false for contain : 当我运行该程序的Validate方法返回truecontainer对象,并返回falsecontain 在此处输入图片说明

But the Container contains an invalid contain object(because its Code property set to null ), and so I want the Validate method don't validate it. 但是Container包含一个无效的contain对象(因为其Code属性设置为null ),因此我希望Validate方法不对其进行验证。

Is the any way to do this? 有什么办法吗?

TryValidateObject method doesn't work recursively. TryValidateObject方法无法递归工作。 Documentation says: 文档说:

This method evaluates each ValidationAttribute instance that is attached to the object type. 此方法评估附加到对象类型的每个ValidationAttribute实例。 It also checks whether each property that is marked with RequiredAttribute is provided. 它还检查是否提供了标有RequiredAttribute的每个属性。 It does not recursively validate the property values of the object. 不会递归地验证对象的属性值。

The workaround is to write your own recursive version of TryValidateObject method. 解决方法是编写您自己的TryValidateObject方法的递归版本。 Another solution is a custom validation attribute. 另一个解决方案是自定义验证属性。 For details see this question . 有关详细信息,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM