我有一个ViewModel,它具有[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..??
,所以我需要从视图模型得到UserID
(在这种情况下)。我怎样才能做到这一点?
你想使用反射来走视图模型实例的属性和查询每个'PropertyInfo'的自定义属性,看看'KeyAttribute'上存在。 [这个问题](http://stackoverflow.com/questions/390594/c-sharp-setting-property-values-through-reflection-with-attributes)涵盖了这个话题。 –
您还需要考虑如果'KeyAttribute'注释多个属性会发生什么情况。 – Jon