I am implementing a custom data annotation and in the main model it works correctly, but when I put the data annotation in the partial metada the validation does not find this data annotation.
my code is as follows:
public partial class register
{
public int id { get; set; }
public long idPerson { get; set; }
public string other { get; set; }
}
public partial class register_Metadata
{
[MyAttributeOne("val1")]
public int id { get; set; }
[MyAttributeOne("val1")]
public long idPerson { get; set; }
public string other { get; set; }
}
The namespace of the two classes is the same.
On the other hand I have a class where I link the two partial classes.
[MetadataType(typeof( register_Metadata))]
public partial class register
{
}
When I validate the field with customized metadata, the propierties function always has 0 results
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var properties = this.GetInvolvedProperties(validationContext.ObjectType);
var numberOfRequiredFields = RequireFromGroupAttribute.GetNumberOfRequiredFields(validationContext.ObjectType, this.Selector);
var values = new List<object> { value };
var otherPropertiesValues = properties.Where(p => p.Key.Name != validationContext.MemberName).Select(p => p.Key.GetValue(validationContext.ObjectInstance));
values.AddRange(otherPropertiesValues);
if (values.Count(s => !string.IsNullOrWhiteSpace(Convert.ToString(s))) >= numberOfRequiredFields)
{
return ValidationResult.Success;
}
return new ValidationResult(this.GetErrorMessage(numberOfRequiredFields, properties.Values), new List<string> { validationContext.MemberName });
}
private Dictionary<PropertyInfo, string> GetInvolvedProperties(Type type)
{
return type.GetProperties()
.Where(p => p.IsDefined(typeof(RequireFromGroupFieldAttribute)) &&
p.GetCustomAttribute<RequireFromGroupFieldAttribute>().Selector == this.Selector)
.ToDictionary(p => p, p => p.IsDefined(typeof(DisplayAttribute)) ? p.GetCustomAttribute<DisplayAttribute>().Name : p.Name);
}
I have changed the data annotation to the main class and then in the properties function I have the two parameters to evaluate. However when I put them in the metadata class it does not work.