我有以下注釋:使用EntityFramework,如何訪問外鍵列的DisplayName?
[Display(Name = "NotImportant", ResourceType = typeof(MyResxFile))]
public int? PhoneModel { get; set; } // this is the id
[Display(Name = "Important", ResourceType = typeof(MyResxFile))]
public virtual PhoneModel PhoneModel1 { get; set; } // this is the object
我用下面的方法來獲取顯示名稱:
PropertyInfo pi = SomeObject.GetProperties[0]; // short example
columnName = ReflectionExtensions.GetDisplayName(pi);
它適用於所有列除了代碼發現沒有自定義/顯示屬性的即使明確存在一個屬性,也可以使用PhoneModel1等列。它適用於int?但我不需要標頭爲ID,我需要PhoneModel1中實際值的標頭。
public static class ReflectionExtensions
{
public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
where T : Attribute
{
var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();
if (attribute == null && isRequired)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The {0} attribute must be defined on member {1}",
typeof(T).Name,
member.Name));
}
return (T)attribute;
}
public static string GetDisplayName(PropertyInfo memberInfo)
{
var displayAttribute = memberInfo.GetAttribute<DisplayAttribute>(false);
if (displayAttribute != null)
{
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);
return entry.Value.ToString();
}
else
{
var displayNameAttribute = memberInfo.GetAttribute<DisplayNameAttribute>(false);
if (displayNameAttribute != null)
{
return displayNameAttribute.DisplayName;
}
else
{
return memberInfo.Name;
}
}
}
}
非常感謝,你讓我的一天!神奇的是使用GetName()而不是.Name –
不客氣。 'GetName()'是魔術;-) – CodeNotFound