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.


  • Android Timezone.getDefault() gives Asia/Calcutta and not Asia/Kolkata
  • Service or property not registered error
  • How to convert date time in hex in android
  • With EntityFramework, how to access DisplayName for foreign key columns?
  • java: how to get Timezone abbreviation (from offset)?
  • CLISP - Reversing a simple list
  • Sum each column for a table with over 20 columns without writing out each sum
  • Node.js: When do you know when a collection of asynchronous tasks is done?
  • Search Facebook by first name with Koala
  • Get highest value from a file using mSL and mIRC
  • How to enforce project-wide unique ids/error codes for easily finding the origin of the error in sou
  • Windows/C# system-level sequential number generator?
  • How to put all my selected columns into a dummy variable?
  • Finding max value in CUDA
  • incomplete type 'struct' error in C
  • SyntaxError: (irb):26: both block arg and actual block given
  • Salesforce Different WSDL files and when to use
  • Combining two different ActiveRecord collections into one
  • saving file generated by TCPDF
  • How to view images from protected folder with php?
  • Automatically associate new Sonar project with custom quality profile and quality gate
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • Textfile Structure (tables)
  • Time complexity of a program which involves multiple variables
  • Checking free space on FTP server
  • C++ Partial template specialization - design simplification
  • NHibernate Validation Localization with S#arp Architecture
  • req.body is undefined - nodejs
  • HTML download movie download link
  • Bug in WPF DataGrid
  • sending/ receiving email in Java
  • vba code to select only visible cells in specific column except heading
  • Redux, normalised entities and lodash merge
  • How to delete a row from a dynamic generate table using jquery?
  • Proper way to use connect-multiparty with express.js?
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • how does django model after text[] in postgresql [duplicate]
  • Checking variable from a different class in C#