I need to get the ApplicationDbContext within a Model.
I am creating a ValidationAttribute. That validation will check some records on database and generate an error if necessary.
public class MyModel
{
public int? ID { get; set; }
[MyValidationForName]
public string Name { get; set; }
}
public class MyValidationForName : ValidationAttribute
{
protected ValidationResult IsValid(object value, ValidationContext validationContext)
{
/* code here */
return new ValidationResult("This field contains an error");
}
}
The example above generates an error (DataAnnotation) when saving the record. It is okay only to check dates, lenghts, etc.
But I have to query some records on database. To perform that, the DB context can not be passed to the model.
All SO topics I've read explains how to validate with Remote and JS, putting the validation on the Controller. I do not want this.
The most related SO topic is: Using DB Context in a Custom Validation Attribute (by adding the context it still not work)
Can anyone help me to pass the ApplicationDbContext to the model to perform queries and validate it with ValidationAttribute?