With EntityFramework, how to access DisplayName for foreign key columns?

I have the following annotations :

[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

I use the following method to get the display name :

PropertyInfo pi = SomeObject.GetProperties[0]; // short example columnName = ReflectionExtensions.GetDisplayName(pi);

It works for all columns <strong>except</strong> the code finds no custom/display attribute for columns such as PhoneModel1 even if there is clearly one attribute. It works for the <strong>int?</strong> but I don't need the header for the <strong>id</strong>, I need the header for the actual value, which is in 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; } } } }


Your GetDisplayName extension method should look like this:

public static string GetDisplayName(this PropertyInfo pi) { if (pi == null) { throw new ArgumentNullException(nameof(pi)); } return pi.IsDefined(typeof(DisplayAttribute)) ? pi.GetCustomAttribute<DisplayAttribute>().GetName() : pi.Name; }

And to use it:

PropertyInfo pi = SomeObject.GetProperties[0]; string columnName = pi.GetDisplayName();

Note that if the property doesn't define a DisplayName attribute we return the property name.


Try this:

var attribute =typeof(MyClass).GetProperty("Name").GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().Single(); string displayName = attribute.DisplayName;

Hopefully It's help for you.

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:With EntityFramework, how to access DisplayName for foreign key columns?