繁体   English   中英

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

[英]FluentValidator extension method to check if entity exists in database

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

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>(); 
    }
}

我有同样的问题并最终这样做

    public static IRuleBuilderOptions<T, Guid> MustExistInDatabase<T, TEntity>(this IRuleBuilder<T, Guid> ruleBuilder, DbSet<TEntity> dbSet) where TEntity : class
    {
        return ruleBuilder.Must(id => dbSet.Find(id) != null).WithMessage("'{PropertyName}' {PropertyValue} not found.");
    }

然后

RuleFor(r => r.EmployeeId).NotEmpty().MustExistInDatabase(context.Employees);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM