我有一个带有3个主键的表(联结表),因此当我想检查重复记录时,我必须一起检查3个属性
我写了一个这样的方法
private bool IsDuplicate(long roleId, long componentGroupId, long operationId)
{
var business = new RoleGroupBusiness();
var result = business.Where(x => x.RoleID == roleId && x.ComponentGroupID == componentGroupId && x.OperationID == operationId).Any();
return result;
}
我有一个像这样的FluentValidator类:
public class RoleGroupValidator : AbstractValidator<RoleGroup>
{
private bool IsDuplicate(long roleId, long componentGroupId, long operationId)
{
var business = new RoleGroupBusiness();
var result = business.Where(x => x.RoleID == roleId && x.ComponentGroupID == componentGroupId && x.OperationID == operationId).Any();
return result;
}
public RoleGroupValidator()
{
RuleFor(x => x.RoleID).NotNull().WithMessage("A");
RuleFor(x => x.ComponentGroupID).NotNull().WithMessage("A");
RuleFor(x => x.OperationID).NotNull().WithMessage("A");
}
}
1)我如何在FluentValidator中使用IsDuplicate methid?
或
2)在fluentValidation库中,检查实体的最佳方式是重复还是不重复?
RuleFor只获取其中一个属性的值,但我需要传递给我的方法的所有属性的值
答案 0 :(得分:9)
你应该使用Must方法:
public class RoleGroupValidator : AbstractValidator<RoleGroup>
{
public RoleGroupValidator()
{
RuleFor(x => x.RoleID).NotNull().WithMessage("A");
RuleFor(x => x.ComponentGroupID).NotNull().WithMessage("A");
RuleFor(x => x.OperationID).NotNull().WithMessage("A");
RuleFor(x => x).Must(x => !IsDuplicate(x));
}
private bool IsDuplicate(RoleGroup r)
{
var business = new RoleGroupBusiness();
return business.Any(x => x.RoleID == r.RoleID &&
x.ComponentGroupID == r.ComponentGroupID &&
x.OperationID == r.OperationID);
}
}
如果它是一次性的(可能是),请不要忘记处置RoleGroupBusiness实例:
private bool IsDuplicate(RoleGroup r)
{
using (var business = new RoleGroupBusiness())
{
return business.Any(x => x.RoleID == r.RoleID &&
x.ComponentGroupID == r.ComponentGroupID &&
x.OperationID == r.OperationID);
}
}
答案 1 :(得分:2)
此代码尚未经过测试,但我已经做了类似的事情,在方法中使用了一个从未用过任何东西的虚拟值。
private bool NotBeDuplicate(RoleGroup r, long dummy)
{
var business = new RoleGroupBusiness();
var result = business.Where(x => x.RoleID == r.RoleID && x.ComponentGroupID == r.ComponentGroupID && x.OperationID == r.OperationID).Any();
return !result;
}
public RoleGroupValidator()
{
RuleFor(x => x.RoleID).Must(NotBeDuplicate);
}
希望这能指明你正确的方向。