25 lines
683 B
C#
25 lines
683 B
C#
using CH.Dal.Abstractions;
|
|
using FluentValidation;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace CH.Dal.Validators;
|
|
|
|
public class DbEntityExistValidator<TEntity, TValue> : AbstractValidator<TValue>
|
|
where TEntity : class, IHasId<TValue>
|
|
{
|
|
private readonly CHDbContext _dbContext;
|
|
|
|
public DbEntityExistValidator(CHDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
|
|
RuleFor(value => value)
|
|
.NotNull()
|
|
.MustAsync(IsEntityExist)
|
|
.WithMessage("Invalid Entity");
|
|
}
|
|
|
|
private Task<bool> IsEntityExist(TValue id,
|
|
CancellationToken cancellationToken)
|
|
=> _dbContext.Set<TEntity>().AnyAsync(entity => entity.Id!.Equals(id), cancellationToken);
|
|
} |