Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Data Annotation "Display Name" of type Enum

Does anyone know how to access the "Display Name" data annotation of enum types?

I have an enum type with display names

class enum SomethingType {
  [Display(Name = "Type 1")]
  Type1,
  [Display(Name = "Type 2")]
  Type2
}

and a model class that references to it

class ModelClass {
  public SomethingType Type {get; set;}
}

How do I display the display name for the values in ModelClass?

Thanks.

like image 572
Milo Cabs Avatar asked Apr 10 '14 01:04

Milo Cabs


1 Answers

I think you are looking for something like this:

class ModelClass
{
    public SomethingType MyType {get; set;}

    public string TypeName {

        get
        {
            var enumType = typeof(SomethingType);
            var field = enumType.GetFields()
                       .First(x => x.Name == Enum.GetName(enumType, MyType));

            var attribute = field.GetCustomAttribute<Display>();

            return attribute.Name;
        }

}
like image 104
Selman Genç Avatar answered Nov 02 '22 23:11

Selman Genç