I'm coding Entity Framework models and I want to validate incoming data for a given property against a predefined list of allowable values. Based on prior research, I decided the best way to do that is via a customized data annotation attribute, making sure that every property that needs this validation has an accompanying array of values that is passed to this attribute, called "[AllowableValue]"
So I have the following class:
public class className
{
public int Id { get; set; }
[Required]
[AllowableValues(ListOfAllowableValues)]
[MaxLength(2), MinLength(2)]
public string propertyName { get; set; }
[NotMapped]
public string[] ListOfAllowableValues = new string[]
{
"00",
"77",
"ZZ"
};
}
And the following Custom Attribute:
public class AllowableValues : ValidationAttribute
{
string[] _list;
public AllowableValues(string[] list)
{
_list = list;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_list.Contains((string)value))
return ValidationResult.Success;
return new ValidationResult("Invalid value.");
}
}
But, In Visual Studio, when I apply the [AllowableValues] attribute, it is giving me the error: "An object reference is required for the non-static field, method, or property 'className.ListOfAllowableValues.'
My definition calls for an array, and I'm passing it an array. Why is it asking for an object reference?