流畅的验证器检查数据库中是否存在ID为的实体 [英] Fluent validator to check if entity with ID exists in database

查看:16
本文介绍了流畅的验证器检查数据库中是否存在ID为的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个自定义验证器,它将使用OrmLite检查数据库中是否存在实体。问题是,IRuleBuilder的类型参数不能再从用法中推断出来。

我必须这样编写方法调用:

RuleFor(r => r.Id).Exists<DtoName, int, EntityName>()

但我想这样写:

Rulefor(r => r.Id).Exists<EntityName>()

这是因为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);
        }
    }

推荐答案

您需要Custom Validator进行自定义验证才能访问依赖项,如下所示:

RuleFor(x => x.Id)
    .Must(id =>
    {
        using (var db = HostContext.AppHost.GetDbConnection(base.Request))
        {
            return !db.Exists<EntityName>(x => x.Id == id);
        }
    })
    .WithErrorCode("AlreadyExists")
    .WithMessage("...");

我还会考虑只使用服务中的依赖项进行验证:

if (Db.Exists<EntityName>(x => x.Id == request.Id))
    throw new ArgumentException("Already Exists", nameof(request.Id));

这篇关于流畅的验证器检查数据库中是否存在ID为的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆