mercredi 5 août 2015

attribute on virtual property not showing via reflection

I have an EntityFramework model with attributes, which I use to validate the fields.

private person tipProvider;
[Required]
[ForeignKey("TipProviderId")]
public virtual person TipProvider
{
    get { return tipProvider; }
    set
    {
        tipProvider = value;
        ValidateProperty(MethodBase.GetCurrentMethod().Name.Replace("set_", ""));
        raisePropertyChanged(MethodBase.GetCurrentMethod().Name.Replace("set_", ""));
    }
}

I get the PropertyInfo and then its validation attributes, which I use to validate the property:

public virtual void ValidateProperty(string property)
{
    errors[property].Clear();
    var propertyInfo = this.GetType().GetProperty(property);
    var propertyValue = propertyInfo.GetValue(this);
    var validationAttributes = propertyInfo.GetCustomAttributes(true).OfType<ValidationAttribute>();
    foreach (var validationAttribute in validationAttributes)
    {
        if (!validationAttribute.IsValid(propertyValue))
        {
            errors[property].Add(validationAttribute.FormatErrorMessage(string.Empty));
        }
    }
    raiseErrorsChanged(property);
}

When the property is virtual, I cannot find the attributes via reflection. If the virtual keyword is removed, the attributes are found.

I'm really confused by this behavior. Why can't attributes be applied on virtual properties?





Aucun commentaire:

Enregistrer un commentaire