0
當我有2個不同的父子規則集時,子類的屬性驗證不起作用。企業驗證爲父級子類阻止不同的子集
這是類代碼:MyType的是家長和人是孩子
[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,但爲True)
[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);
}
Wou你可以幫忙嗎?
我想你應該從'[ObjectValidator]'中刪除'Ruleset =「RulesetA」'。只需使用'[ObjectValidator]'裝飾該屬性即可。這可以確保'Person'總是得到驗證。 – Steven
不,它仍然失敗:( – mk78
當你添加'[ObjectValidator(「RulesetB」,Ruleset =「RulesetB」)]'(和'RulesetA')到'Person'屬性嗎? – Steven