gla*_*oon 3 fluentvalidation servicestack
我正在尝试编写一个自定义验证器,它将使用 OrmLite 检查数据库中是否存在实体。问题是 IRuleBuilder 的类型参数无法再从使用中推断出来。
我必须像这样编写方法调用:
RuleFor(r => r.Id).Exists<DtoName, int, EntityName>()
Run Code Online (Sandbox Code Playgroud)
但我想这样写:
Rulefor(r => r.Id).Exists<EntityName>()
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为 IRuleBuilder 有两个类型参数,并且该方法是扩展方法。是否有一种聪明、流畅的方法来设计这个并使函数调用最好像第二个版本一样?
这是我的扩展方法和验证器的代码:
public static class AbstractValidatorExtensions
{
public static IRuleBuilderOptions<T, TProperty> Exists<T, TProperty, U>(this IRuleBuilder<T, TProperty> ruleBuilder)
{
return ruleBuilder.SetValidator(new EntityExistsValidator<U>());
}
}
public class EntityExistsValidator<T> : PropertyValidator
{
public EntityExistsValidator() : base("Entity does not exist") {}
protected override bool IsValid(PropertyValidatorContext context)
{
return HostContext.Resolve<Repository>()
.Exists<T>((int)context.PropertyValue);
}
}
Run Code Online (Sandbox Code Playgroud)
tho*_*ker 14
我对 FluentValidation 的经验是,您\xe2\x80\x99 正在尝试将越来越多的逻辑推送到验证器中。我不会这样做,因为它增加了太多的复杂性。我的经验法则是仅验证离散属性值。示例:我只是使用 FluentValidation 来检查属性 int Id 是否为 0 或大于 0。检查实体是否已存在我将转移到另一个服务(通常称为 \xe2\x80\x9c 业务逻辑 \xe2\x80\x9d )。
\n| 归档时间: |
|
| 查看次数: |
13360 次 |
| 最近记录: |