(最佳实践)FluentValidation和检查重复实体 [英] (Best Practice) FluentValidation and Checking Duplicate Entities
问题描述
我有一个带有3个主键的表(连接表),因此当我要检查重复记录时,必须一起检查3个属性
I have a table (junction table) with 3 primary keys so when I want to check duplicate records , I must check 3 properties together
我写了这样的方法
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类:
and I have a FluentValidator class like this :
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方法?
1) How can i use IsDuplicate methid in FluentValidator ?
或
2)检查实体的最佳方法是在fluentValidation库中是否重复?
2) What is best way for checking entity is Duplicate or not in fluentValidation Library ?
RuleFor只让我获得其中一个属性的值,但我需要所有属性的值才能传递给我的方法
RuleFor only get me value of one of properties but I need value of all properties for passing to my method
推荐答案
您应使用Must方法:
You should use Must method:
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实例:
Don't forget to dispose RoleGroupBusiness instance if it's disposable(it probably is):
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);
}
}
这篇关于(最佳实践)FluentValidation和检查重复实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!