0

In the Database context, when accessing properties before calling SaveChanges, how do I get the Displayname rather than simply the name (the below code)?

string changes = "";
foreach (var item in ctx.Entry(entity).Properties)
{
    if (item.IsModified)
    {
        changes += "["+item.Metadata.Name+"]";
    }
}
jps
  • 20,041
  • 15
  • 75
  • 79
Peter
  • 1
  • display name of the property? you mean name mentioned in `Display` attribute? like `[Display(Name="some name")]` ? – Aarif Apr 12 '19 at 09:50
  • 1
    maybe this can help https://stackoverflow.com/a/5015878/6027876 – Aarif Apr 12 '19 at 10:03
  • Thanks, that got me a little further. When I do this: var attribute = item.Metadata.PropertyInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true); the debugger tells me I have {System.ComponentModel.DisplayNameAttribute[0]} and attribute.GetType() gives me (shortened): {System.ComponentModel.DisplayNameAttribute[]} AssemblyQualifiedName: "System.ComponentModel.DisplayNameAttribute[], Name: "DisplayNameAttribute[]" {System.ComponentModel.DisplayNameAttribute[]} But attribute.Cast().SingleOrDefault(); gives null – Peter Apr 15 '19 at 06:31
  • try this answer: https://stackoverflow.com/a/32808219/6027876 – Aarif Apr 15 '19 at 07:03
  • Thanks, that got me close enough; in my case, this works: var fieldName = item.Metadata.Name; MemberInfo property = typeof(ApplicationForm).GetProperty(item.Metadata.Name); var ca = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute; if (ca != null) { fieldName = ca.Name; } – Peter Apr 15 '19 at 11:26
  • you're welcome, glad to help. – Aarif Apr 15 '19 at 11:26

0 Answers0