簡體   English   中英

如何獲取 DataAnnotation 顯示名稱?

[英]How to get DataAnnotation Display Name?

我有 EF 模型類。 為此,我為該部分類創建了MetadataType

現在我需要從 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;

在這里,我想在迭代中獲取所有屬性 displayname。 所以我可以將它們添加到 excel 標題行和單元格中。 怎么做?

ReflectionLINQ是你的朋友

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

注意:您需要在項目中包含System.ReflectionSystem.Linq命名空間才能使用這些方法。

ASP.NET 核心 2:

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

只需這樣做:

private string GetDisplayName(vwGridMetadata data, Object vwGridMetadataPropertie)
{
    string displayName = string.Empty;

    string propertyName = vwGridMetadataPropertie.GetType().Name;

    CustomAttributeData displayAttribute = data.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");

    if (displayAttribute != null)
    {
        displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
    }

    return displayName;
}

您可以創建一個 foreach 來循環遍歷 vwGridMetadata 類屬性並在每個屬性上調用此方法,或者只是在內部創建一個 foreach 並從該方法中刪除 Object 參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM