Search code examples
c#system.reflection

Get property from attribute value


Having this simple class:

public class Book
{
    [DataMember]
    [Column("Bok_Name")]
    [Author("AuthorName")]
    public string Name{ get; set; }

    [DataMember]
    [Column("Bok_Publisher")]
    public string Publisher{ get; set; }
}

How can i can get the PropertyInfo from a property knowing that the attribute type is Column and the value is Bok_Name. I has trying to do this with a linq query.


Solution

  • Using reflection and the .NET extension CustomAttributeExtensions.GetCustomAttribute{T} method, you can find the properties with the custom attribute. In this case, the custom attribute is from System.ComponentModel.DataAnnotations.Schema.ColumnAttribute.

    var book = new Book { Name = "Jitterbug Perfume" };
    
    PropertyInfo bokName = typeof(Book)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance) // add other bindings if needed
        .FirstOrDefault(x => x.GetCustomAttribute<ColumnAttribute>() != null
           && x.GetCustomAttribute<ColumnAttribute>().Name.Equals("Bok_Name", StringComparison.OrdinalIgnoreCase));
    
    // the above query only gets the first property with Column attribute equal to "Bok_Name"
    // if there are more than one, then use a .Where clause instead of FirstOrDefault.
    if (bokName != null)
    {
        string name = bokName.GetValue(book).ToString();
        // do other stuff
    }