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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.