dotnet-digital-ops/DigitalOps.Dal/Validators/DbEntityExistValidator.cs

25 lines
703 B
C#
Raw Normal View History

2025-01-02 15:10:52 -05:00
using DigitalOps.Dal.Abstractions;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
namespace DigitalOps.Dal.Validators;
public class DbEntityExistValidator<TEntity, TValue> : AbstractValidator<TValue>
where TEntity : class, IHasId<TValue>
{
private readonly MainDbContext _dbContext;
public DbEntityExistValidator(MainDbContext 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);
}