Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection, get DataAnnotation attributes from buddy class

I need to check if property has specific attribute defined in its buddy class:

[MetadataType(typeof(Metadata))]
public sealed partial class Address
{
    private sealed class Metadata
    {
        [Required]
        public string Address1 { get; set; }

        [Required]
        public string Zip { get; set; }
    }
}

How to check what properties has defined Required attribute?

Thank you.

like image 499
Feryt Avatar asked Feb 27 '23 05:02

Feryt


1 Answers

It can be done using exploration of nested types:

public IEnumerable<PropertyInfo> GetRequiredProperties()
{
    var nestedTypes = typeof(Address).GetNestedTypes(BindingFlags.NonPublic);

    var nestedType = nestedTypes.First(); // It can be done for all types

    var requiredProperties =
        nestedType.GetProperties()
            .Where(property => 
                           property.IsDefined(typeof(RequiredAttribute), false));

    return requiredProperties;
}

Usage example:

[Test]
public void Example()
{
    var requiredProperties = GetRequiredProperties();
    var propertiesNames = requiredProperties.Select(property => property.Name);

    Assert.That(propertiesNames, Is.EquivalentTo(new[] { "Address1", "Zip" }));
}
like image 95
Elisha Avatar answered Mar 06 '23 23:03

Elisha