从ViewModel获取[key]属性

w00*_*w00 5 c# annotations key

我有一个ViewModel,它有一个[key]属性,我想从该视图模型的实例中获取它.

我的代码看起来像这样(虚构的模型)

class AddressViewModel
{
    [Key]
    [ScaffoldColumn(false)]
    public int UserID { get; set; } // Foreignkey to UserViewModel
}

// ... somewhere else i do:
var addressModel = new AddressViewModel();
addressModel.HowToGetTheKey..??
Run Code Online (Sandbox Code Playgroud)

所以我需要UserID从ViewModel中获取(在本例中).我怎样才能做到这一点?

Ada*_*rth 8

如果您对示例中的任何代码感到困惑或困惑,只需删除评论,我会尽力提供帮助.

总之,您有兴趣使用Reflection来遍历类型的元数据,以获取分配了给定属性的属性.

下面只是这样做的一种方式(还有许多其他方法以及提供类似功能的许多方法).

从这个问题中我把评论链接起来:

PropertyInfo[] properties = viewModelInstance.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{
    var attribute = Attribute.GetCustomAttribute(property, typeof(KeyAttribute)) 
        as KeyAttribute;

    if (attribute != null) // This property has a KeyAttribute
    {
         // Do something, to read from the property:
         object val = property.GetValue(viewModelInstance);
    }
}
Run Code Online (Sandbox Code Playgroud)

像乔恩所说,处理多个KeyAttribute声明以避免问题.此代码还假定您正在装饰public属性(不是非公共属性或字段)和要求System.Reflection.