Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DB Context in a Custom Validation Attribute

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;
        }        
    }
}
like image 240
Matthew Warr Avatar asked Jan 18 '18 09:01

Matthew Warr


1 Answers

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));
like image 142
Matthew Warr Avatar answered Oct 19 '22 23:10

Matthew Warr