25 lines
703 B
C#
25 lines
703 B
C#
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);
|
|
} |