Search code examples
c#asp.net-coreentity-framework-core

Getting the Column Name mapping component of an EF Core Class property?


I have the following EF Core class:

public partial class myClass
{
    public string ID { get; set; }
    [Column("Team 17")]
    public bool? Team17 { get; set; }
    [Column("Team 158")]
    public bool? Team158 { get; set; }
}

I would like to iterate over the properties of this class and obtain the Column Name component of each. So, for example, for the Team17 column I would to get "Team 17". How can this be done?

I already have this code for deriving the Name of each property:

foreach (PropertyInfo p in typeof(myClass).GetProperties()) 
{
    Console.WriteLine(p.Name);
}

Solution

  • You can use the GetCustomAttributes method to check if each property has the ColumnAttribute attribute and retrieve it if it exists.

       foreach (PropertyInfo p in typeof(myClass).GetProperties())
        {
            var columnAttribute = p.GetCustomAttributes(typeof(ColumnAttribute), false)
                               .FirstOrDefault() as ColumnAttribute;
        
            if (columnAttribute != null)
            {
                Console.WriteLine(columnAttribute.Name);
            }
            /*else
            {
                Console.WriteLine(p.Name);
            }*/
        }
    

    result