2016-04-11 83 views
1

我正在使用实体框架,这里是其中一个表的元数据外观。获取实体的列名

[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; } 

我有兴趣获取Column属性名称而不是公共名称,即显示pp_added而不是“AddDate”。这里是一个foreach循环我已经写到目前为止,几乎让我有

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"); 
} 

下面是返回什么:

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

我希望得到什么回是

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

如何访问[Column("pp_added")]以获取pp_added而不是公众Name

+0

您需要使用反射。有关详细信息,请参阅http://stackoverflow.com/questions/9113020/get-attribute-info-with-generics – mit

+0

基于反射的方法在流利的API情况下不起作用。你需要探索EF元数据。 – Dennis

回答

4

这应该工作:

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"); 
} 

ColumnAttribute是在System.ComponentModel.DataAnnotations.Schema命名空间。

+0

但他说“field.Name”不会返回预期值。 –

+0

我没有使用该字段的名称属性,但列属性为 –

+0

非常感谢。那就是诀窍。我非常感谢你的帮助。 –

1

除了亚历山大的回答,这将让底层的类型可空类型:

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

Nullable.GetUnderlyingType将返回底层的类型,如果它是空(也就是说它会返回DateTime,如果给DateTime?)或者如果不可为空则返回null。因此,??表达式。

+0

这是我的下一个问题,如果我找不到它。提前感谢您的答案,并节省了我在寻找和尝试的两天时间。我非常感谢。 –