我有以下需要更改的FluentValidation代码,以便验证调用IsUniqueCode函数并传递currentID参数,该参数是已验证的Language对象的id。
public class LanguageValidator : AbstractValidator<Language>
{
public LanguageValidator()
{
RuleFor(x => x.Code).NotEmpty().WithMessage("Language code is required").Length(0, 100);
RuleFor(x => x.Code).Must(IsUniqueCode).WithMessage("Language code provided already exists");
}
private bool IsUniqueCode(string code, int currentID)
{
var _db = new MyDbContext();
var language = _db.Languages.SingleOrDefault(x => x.Code == code);
if (language== null) return true;
return (language.LanguageId != currentID);
}
}
这是第二次保存对象时,它所提供的语言代码已经存在的验证不会失败。
由于
,上述代码无法编译RuleFor(x => x.Code)
.Must(**IsUniqueCode**)
.WithMessage("Language code provided already exists");