4

I'm using Entity Framework and here is what the metadata looks like for one of the tables.

    [Column("pp_account")]
    public string Account { get; set; }
    [Column("pp_added")]
    public DateTime? AddDate { get; set; }
    [Column("pp_auser")]
    public string AddUpdateUserName { get; set; }
    [Column("pp_cfalt")]
    public string AlternateForwardingNumber { get; set; }

I'm interested in getting the Column attribute name instead of the public name, i.e. display pp_added instead of "AddDate". Here is a foreach loop I've written so far that almost gets me there

foreach(var field in _personal.GetType().GetProperties())
{
            sb.Append("\nName            : " +  field.Name + "\n");
            sb.Append("Type        : " + field.PropertyType.Name + "\n");
            sb.Append("Attributes:  " + field.Attributes + "\n");
            sb.Append("Value       : " + field.GetValue(_personal, null) + "\n");
}

Here is what is returned:

Name:  AddDate
Type:  Nullable'1
Attributes:  None
Value:  5/2/2014 12:00:00 AM

What I would like to get returned is

Name:  pp_added
Type:  Date
Value:  5/2/2014 12:00:00 AM

How do I access the [Column("pp_added")] to get pp_added instead of the public Name?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Todd Miller
  • 189
  • 2
  • 9
  • You need to use reflection. See more in http://stackoverflow.com/questions/9113020/get-attribute-info-with-generics – mit Apr 11 '16 at 13:20
  • Reflection-based approach won't work in fluent API case. You need to explore EF metadata. – Dennis Apr 11 '16 at 13:23

2 Answers2

13

This should work:

foreach(var field in _personal.GetType().GetProperties())
{
   sb.Append("\nName       : " +  field.GetCustomAttribute<ColumnAttribute>().Name + "\n");
   sb.Append("Type        : " + field.PropertyType.Name + "\n");
   sb.Append("Value       : " + field.GetValue(_personal, null) + "\n");
}

The ColumnAttribute is in the System.ComponentModel.DataAnnotations.Schema namespace.

Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
3

In addition to Alexander's answer, this will get the underlying type for the nullable type:

sb.Append("Type        : " + (Nullable.GetUnderlyingType(field.PropertyType) ?? field.PropertyType).Name + "\n");

Nullable.GetUnderlyingType will return the underlying Type if it is nullable (i.e. it will return DateTime, if given DateTime?), or return null if it's not nullable. Hence, the ?? expression.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • 1
    That was going to be my next question if I couldn't find it. Thanks for the answer ahead of time and saving me the 2 days of looking and trying. I very much appreciate it. – Todd Miller Apr 11 '16 at 16:24