2014-04-10 8 views
5

Qualcuno sa come accedere all'annotazione dati "Nome visualizzato" dei tipi enum?Annotazione dati Entity Framework "Nome visualizzato" del tipo Enum

Ho un tipo enum con nomi visualizzati

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

e una classe modello che riferimenti ad esso

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

Come faccio a visualizzare il nome di visualizzazione per i valori in ModelClass?

Grazie.

risposta

6

penso che siete alla ricerca di qualcosa di simile:

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; 
     } 

} 
+1

mi piace questo, ma sto ancora aspettando risposte migliori –

1

Si potrebbe utilizzare la reflection per accedere alle proprietà dell'attributo:

Type = SomethingType.Type2; 

var memberInfo = Type.GetType().GetMember(Type.ToString()); 

if (memberInfo.Any()) 
{ 
    var attributes = memberInfo.First().GetCustomAttributes(typeof(DisplayAttribute), false); 
    if (attributes.Any()) 
    { 
     var name = ((DisplayAttribute)attributes.First()).Name; // Type 2 
    } 
} 
1

è possibile creare un metodo di supporto generico che leggerà i dati da questi attributi.

public static string GetAttributeValue<T>(this Enum e, Func<T, object> selector) where T : Attribute 
    { 

     var output = e.ToString(); 
     var member = e.GetType().GetMember(output).First(); 
     var attributes = member.GetCustomAttributes(typeof(T), false); 

     if (attributes.Length > 0) 
     { 
      var firstAttr = (T)attributes[0]; 
      var str = selector(firstAttr).ToString(); 
      output = string.IsNullOrWhiteSpace(str) ? output : str; 
     } 

     return output; 
    } 

Esempio:

var x = SomethingType.Type1.GetAttributeValue<DisplayAttribute>(e => e.Name); 

.......

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

    public string TypeName 
    { 
     get { return Type.GetAttributeValue<DisplayAttribute>(attribute => attribute.Name); } 
    } 
} 
+1

Sono sorpreso che nessuno ha votato questa risposta in alto o meglio ancora accettato come risposta. –