我有以下三个实体,它们相互链接如下:
class Class1
{
int id { get; set; }
Class2 { get; set; }
}
class Class2
{
int id { get; set; }
Class3 { get; set; }
}
class Class3
{
int id { get; set; }
Class1 { get; set; }
}
现在我为这些类中的每一个创建了验证器,并且还SetValidator
为链接到它们的实体创建了验证器:
//Class1 (and other classes) validator has following rules:
public class Class1Validator()
{
public Class1Validator()
{
RuleFor(x => x.id).NotEqual(0).WithMessage("id is required.");
RuleFor(x => x.Class2).SetValidator(new Class2Validator());
}
}
public class Class2Validator()
{
public Class2Validator()
{
RuleFor(x => x.id).NotEqual(0).WithMessage("id is required.");
RuleFor(x => x.Class3).SetValidator(new Class3Validator());
}
}
public class Class3Validator()
{
public Class3Validator()
{
RuleFor(x => x.id).NotEqual(0).WithMessage("id is required.");
RuleFor(x => x.Class1).SetValidator(new Class1Validator());
}
}
//Now when following is called:
var validator = new Class1Validator();
当我检查 validate forClass1
时,它还包含验证器 forClass2
然后Class2
有 for Class3
,最后Class3
还有验证器,Class1
它形成一个无限循环并抛出以下错误:
mscorlib.dll 中出现“System.StackOverflowException”类型的未处理异常
并在查看完整详细信息时显示:
无法计算表达式,因为当前线程处于堆栈溢出状态。
对此有任何解决方案还是我在这里做错了什么?
更新:我还尝试了以下方法,如果对象为空,我可以限制验证器,但这不起作用:
When(x => x.Class1 != null, () => RuleFor(x => x.Class1).SetValidator(new Class1Validator()));