6

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;
        }        
    }
}

1 Answer 1

19

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.