Search code examples
c#metadatacaption

Implement a Caption Property in a Model Entity?


Recently we are converting Datatable to List of Models.. I had a class called Person ( personid ,PersonChildId} and I implemented my class as

public class Person 
{
    public Int64 PerosnId{ get; set; }
    public Int64 PersonChildID{ get; set; }
}

I sucessfully converted my Datatable to List<Person> by using simple for loop. But now the problem is as we know Datacolumn has a property called Caption. but unfortunately models don't have.
So how do we need implement a Caption property for the Model for these kind of scenarios.


Solution

  • Use an attribute like the DisplayName:

    public class Person 
    {
        [DisplayName("Person ID:"]
        public Int64 PerosnId{ get; set; }
    
        [DisplayName("Person Child ID:"]
        public Int64 PersonChildID{ get; set; }
    }
    

    You can get the value of the attribute with:

    var caption = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
          .Cast<DisplayNameAttribute>.Single().DisplayName;