I'm trying to make a custom validation [IsUnique]. That check if is property value is unique and return a proper message.
This is my code, but this only work for a specified class, is possible to do a method that get the proper class by the metadata?
public class ArticleMetaData
{
[Required(AllowEmptyStrings = false)]
[IsUnique("Name")]
public String Name{ get; set; }
}
And my custom validation:
class IsUnique : ValidationAttribute
{
public IsUnique(string propertyNames)
{
this.PropertyNames = propertyNames;
}
public string PropertyNames { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var myproperty = validationContext.ObjectType.GetProperty(PropertyNames);
var value = propiedad.GetValue(validationContext.ObjectInstance, null);
IEnumerable<String> properties;
List<string> propertiesList = new List<string>();
propertiesList.Add(myproperty.Name);
var dba = new myContext();
if (dba.Articles.Any(article => article.Name == (string)value))
{
return new ValidationResult("The name already exist", propertiesList);
}
return null;
}
}
the idea would be to just use the annotation [isUnique] and the method take the class with annotation and search the corresponding entity.