Determine which properties in a class has a special attribute

Viewed 66

I have a class with some property like this:

public List<Some1POCO> SomeProp1List{ set; get; }

[SomeAttribute]
public List<Some2POCO> SomeProp2List { set; get; }
.
.
.

I want to find out properties that has "SomeAttribute" and then include this properties in a EF query

how to use it as a condition in LINQ queries ?

1 Answers

This example works if TClass has exactly one property with SomeAttribute and TProp is a reference type.

You can use this function in LINQ queries as you would with every other function.

TProp GetValueOfPropertyWithSomeAttribute<TClass, TProp>(TClass entity)
  where TClass : class
  where TProp : class
{
  return typeof(TClass)
    .GetProperties()
    .Single(pi => Attribute.IsDefined(pi, typeof(SomeAttribute), false))
    .GetMethod
    .Invoke(entity, null) as TProp;
}
Related