我有这些课程
public class Shape
{
public Shape()
{
ShapeDetails = new List<ShapeDetail>();
}
public int ID { get; set; }
public string Name { get; set; }
public List<ShapeDetail> ShapeDetails { get; set; }
}
public class ShapeValidator : AbstractValidator<Shape>
{
public ShapeValidator()
{
RuleFor(x => x.Name).NotEmpty().Length(1, 225);
}
}
public class ShapeDetail
{
public int ID { get; set; }
public decimal RangeFrom { get; set; }
public decimal RangeTo { get; set; }
public decimal Price { get; set; }
public int ShapeID { get; set; }
[NonPersistent]
public Shape Shape { get; set; }
}
public class ShapeDetailValidator : AbstractValidator<ShapeDetail>
{
public ShapeDetailValidator()
{
RuleFor(x => x.RangeFrom).NotEmpty().LessThan(100);
RuleFor(x => x.RangeTo).NotEmpty().LessThan(100);
RuleFor(x => x.Price).NotEmpty().LessThan(9999999999);
}
}
当我在ModelState.IsValid
上调用Shape
时,它始终返回true,似乎没有验证ShapeDetail
,如何在验证中包括ShapeDetails
? / p>
谢谢
答案 0 :(得分:1)
找到答案,需要在RuleForEach
中添加ShapeValidator
public class ShapeValidator : AbstractValidator<Shape>
{
public ShapeValidator()
{
RuleFor(x => x.Name).NotEmpty().Length(1, 225);
RuleForEach(x => x.ShapeDetails).SetValidator(new ShapeDetailValidator());
}
}