用于检查数据库中是否存在实体的FluentValidator扩展方法

时间:2019-08-20 10:57:36

标签: c# fluentvalidation ef-core-2.2

我有一个非常普遍的情况,我需要验证何时在给定实体中设置了引用属性。发生这种情况时,我会这样验证:

public class Validator : AbstractValidator<Command>
{
    public Validator()
    {
        ...

        RuleFor(user => user.EmployeeId)
            .MustNotBeEmpty() 
            .MustAsync(ExistInDatabase).WithMessage("Employee not found"); 
    }

    public async Task<bool> ExistInDatabase(Command command, string id, CancellationToken cancelation)
    {
        return await _context.Employees.AnyAsync(x => x.Id == id.ToGuid());
    }
}

这种和其他签入数据库非常普遍,我几乎在每个验证器中都编写这样的方法。

我想将其转换为扩展方法,在该方法中,我将传递实体类型,上下文和ID。

FluentValidation扩展方法如下:

public static IRuleBuilderOptions<T, string> MustNotBeEmpty<T>(this IRuleBuilder<T, string> rule)
{
    return rule
        .NotEmpty().WithMessage("O campo '{PropertyName}' não pode ser vazio");
}

但是这些扩展方法已经接受了通用类型,并且我还没有弄清楚如何通过另一个通用类型与context.Set<T>().AnyAsync(...)一起使用

怎么办?

-----更新-----

我尝试将另一种通用类型T2添加到扩展方法中,但是它不起作用:

    public static IRuleBuilderOptions<T, string> MustExistInDatabase<T, T2>(this IRuleBuilder<T, string> rule, DatabaseContext context) where T2: BaseEntity
    {
        return rule.MustAsync(async (command, id, cancelation) => await context.Set<T2>().AnyAsync(x => x.Id == id.ToGuid())).WithMessage("'{PropertyName}' not found in database");
    } 

当我尝试调用它时,编译器抱怨找不到该扩展方法:

public class Validator : AbstractValidator<Command>
{
    public Validator()
    {
        ...

        RuleFor(user => user.EmployeeId)
            .MustNotBeEmpty() 
            .MustExistInDatabase<Employee>(); 
    }
}

0 个答案:

没有答案