流畅验证使用LINQ let
本文关键字:LINQ let 验证 | 更新日期: 2023-09-27 18:12:34
我试图创建一个验证规则,我可以在两个参数传递到一个方法调用Must()
我的模型;
public class Make
{
public int MakeId { get; set; }
public string Name { get; set; }
public Car[] Cars { get; set; }
}
public class Car
{
public int CarId { get; set; }
public string Name { get; set; }
}
验证器
public class MakeValidator : AbstractValidator<Make>
{
public MakeValidator()
{
When(car => car.Cars != null && car.Cars.Any(), () =>
{
RuleFor(car => car.Car)
.Must(car => ValidateCar(car.CarId, MakeId)
.WithMessage("Invalid Car");
});
}
public bool ValidateCar(Car[] Cars, int makeId)
{
foreach (var car in Cars)
{
// *** internal logic ***
}
return true;
}
}
use
Must((y, x) =>
代替
Must(x =>
其中y
代表你的类,x
代表你的属性
为了让事情更清楚
.Must((car, make) => ValidateCarMake(make, car.CarId)
编辑
从你的ValidateCarMake
方法的签名,它应该是
RuleFor(car => car.Makes)
.Must((car, make) => ValidateCarMake(make, car.CarId)
.WithMessage("Invalid Car Make");
或
RuleFor(car => car.Make)
.Must((car, make) => ValidateCarMake(car.Makes, car.CarId)
.WithMessage("Invalid Car Make");