I am trying to create a valdiation attribute in my Core 2 project. It needs to validate the value against a list of existing values held in the database.
The code below isn't working, it isn't able to access the DB Context.
Any ideas why/how to correct?
public class BibValidatorAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        RaceEntryViewModel raceEntry = (RaceEntryViewModel)validationContext.ObjectInstance;
        ApplicationDbContext _context = new ApplicationDbContext();
        var dbraceEntry = _context.RaceEntries.FirstOrDefault(c => c.Id == raceEntry.Id);
        if(raceEntry.BibNumber != dbraceEntry.BibNumber)
        {
            if (value != null)
            {
                var raceentries = from r in _context.RaceEntries
                                  select r;
                var mycount = raceentries.Count(c => c.BibNumber == raceEntry.BibNumber);
                if (mycount != 0)
                {
                    return new ValidationResult("The bib number entered already exists");
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
            else
            {
                return ValidationResult.Success;
            }
        }
        else
        {
            return ValidationResult.Success;
        }        
    }
}
                What i found you can do is retrieve the DB Context from the ValidationContext which I didn't realize you could do using GetService.
var _context = (ApplicationDbContext)validationContext
                         .GetService(typeof(ApplicationDbContext));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With