【发布时间】:2012-10-01 21:40:30
【问题描述】:
我有一个 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..??
所以我需要从 ViewModel 中获取 UserID(在这种情况下)。我该怎么做?
【问题讨论】:
-
你想使用反射来遍历 ViewModel 实例的属性,并查询每个
PropertyInfo的自定义属性以查看其上是否存在KeyAttribute。 This question 涵盖了该主题。 -
您还需要考虑如果
KeyAttribute注释多个属性会发生什么。
标签: c# annotations key