gpt4 book ai didi

c# - (最佳实践)FluentValidation 和检查重复实体

转载 作者:太空狗 更新时间:2023-10-29 18:24:56 25 4
gpt4 key购买 nike

我有一个包含 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 方法?

2) 在 fluentValidation 库中检查实体是否重复的最佳方法是什么?

RuleFor 只获取其中一个属性的值,但我需要所有属性的值才能传递给我的方法

最佳答案

你应该使用 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);
}
}

关于c# - (最佳实践)FluentValidation 和检查重复实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23411933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com