Search code examples
.netpetapoco

What is this the best way to get the real column names from my poco?


I'm using PETAPOCO make a list of generic objects that are then bound to a gridview. However, since the column names are not valid property names, they get changes by the T4 code. I'd like to loop through the gridview columns and changes the header text to show the real column names. What is the best way to get the column attributes of a POCO property when I simply have a string representation of the property name?

For example, I have:

[ExplicitColumns]
public partial class SomeTable : DB.Record<SomeTable>  
{

    [Column("5F")] 
    public int _5F 
    { 
        get {return __5F;}
        set {__5F = value;
            MarkColumnModified("5F");}
    }
    int __5F;
}

I want a routine like:

public string GetRealColumn(string ObjectName, sting PropertyName)

So that: GetRealColumn("SomeTable", "_5F") returns "5F"

Any suggestions?


Solution

  • You can always use reflection to get the attribute that is applied to the property, something along the lines of:

    public string GetRealColumn(string objectName, string propertyName)
    {
       //this can throw if invalid type names are used, or return null of there is no such type
       Type t = Type.GetType(objectName); 
       //this will only find public instance properties, or return null if no such property is found
       PropertyInfo pi = t.GetProperty(propertyName);
       //this returns an array of the applied attributes (will be 0-length if no attributes are applied
       object[] attributes = pi.GetCustomAttributes(typeof(ColumnAttribute));
       ColumnAttribute ca = (ColumnAttribute) attributes[0];
       return ca.Name;
    }
    

    For sake of brevity and clarity I've omited error checking, you should add some to ensure it does not fail at runtime. This is not production quality code.

    Also reflection tends to be slow, so it's best to cache the results.