2014-05-12 55 views
3

我有EF模型類。爲此,我爲該部分類創建了MetadataType如何獲取DataAnnotation顯示名稱?

現在我需要從c#中讀取或獲取所有這些對象屬性的顯示名稱。所以我可以在Excel標題行中使用。

[MetadataType(typeof(vwGridMetadata))] 
public partial class vwGrid 
{ 

} 

public class vwGridMetadata 
{ 
    [Display(Name = "Note ID")] 
    public int intNoteID { get; set; } 
    [Display(Name = "Global Number")] 
    public string strGlobalLoanNumber { get; set; } 
    [Display(Name = "Data Source ID")] 
    public Nullable<int> intDataSourceID { get; set; } 
    [Display(Name = "Sample ID")] 
    .... 
} 

vwGrid grd = new vwGrid;

在這裏,我想獲得所有屬性的迭代顯示名稱。所以我可以將它們添加到excel標題行和單元格中。怎麼做?

回答

10

ReflectionLINQ是你的朋友

typeof(vwGridMetadata) 
.GetProperties() 
.Select(x => x.GetCustomAttribute<Display>()) 
.Where(x => x != null) 
.Select(x => x.Name); 

注:您需要包括爲了使用這些方法System.ReflectionSystem.Linq命名空間到項目中。

+0

簡單好用,不錯的工作。只是說...哈哈 – Tony

0

ASP.Net的Core 2:

var listOfFieldNames = typeof(vwGridMetadata) 
        .GetProperties() 
        .Select(f => f.GetCustomAttribute<DisplayAttribute>()) 
        .Where(x => x != null) 
        .Select(x=>x.Name) 
        .ToList();