title: Using DB Context in a Custom Validation Attribute
body: <p>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.</p>
  
  <p>The code below isn't working, it isn't able to access the DB Context.</p>
  
  <p>Any ideas why/how to correct?</p>
  
  <pre><code>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 =&gt; 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 =&gt; 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;
          }        
      }
  }
  </code></pre>