企业验证阻止父子类的不同规则

时间:2012-10-09 11:09:41

标签: c# .net validation enterprise-library validation-application-bl

当父母和孩子有2个不同的规则集时,对子类的属性进行验证不起作用。

这是类代码:Mytype是父类,Person是小孩

    [HasSelfValidation]
    public class MyType
    {
        [SelfValidation(Ruleset = "RulesetA")]
        [SelfValidation(Ruleset = "RulesetB")]
        public void DoValidate(ValidationResults results)
        {
        }

        [NotNullValidator(Ruleset = "RulesetA")]
        [ObjectValidator("RulesetA", Ruleset = "RulesetA")]
        public Person Person { get; set; }

    }

    public class Person
    {
        [NotNullValidator(Ruleset = "RulesetB")]
        public string GivenName { get; set; }

    }

这是针对所有规则集验证MyType类的自定义验证程序类:

    public interface IValidator<T>
    {
        ValidationResults Validate(T target);
    }

    public class MyValidator : IValidator<MyType>
    {
        public ValidationResults Validate(MyType target)
        {
            return Validation.Validate(target, new string[] {"RulesetA", "RulesetB"});
        }
    }

这是失败的测试:( IsValid应该设置为False,但它是真的)

    [TestMethod]
    public void Should_return_false_when_validating_MyType_without_PersonApplying_GivenName()
    {
        //arrange
        var myType = new MyType()
                            {
                                Person= new Person()
                            };
        myType.Person.GivenName = null;

        //act
        MyValidator _validator = new MyValidator();
        var resultList = _validator.Validate(myType);

        //assert
        Assert.IsFalse(resultList.IsValid);
    }
你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

VAB按规则集验证您的对象并连接验证结果。这就是Validation.Validate方法的样子:

var resultsReturned = new ValidationResults();

foreach (string ruleset in rulesets)
{
    var validator = ValidationFactory.CreateValidator(
        targetType, ruleset, source);

    foreach (var validationResult in validator.Validate(target))
    {
        resultsReturned.AddResult(validationResult);
    }
}

return resultsReturned;

换句话说,始终对单个规则集执行对象的验证。由于ObjectValidator仅为RulesetA修饰,因此在Person上运行时,RulesetB对象将无法验证。