MVC3:获取KeyAttribute

发布于 2024-12-20 18:19:47 字数 190 浏览 0 评论 0原文

在提供的模型(类)中查找哪个属性具有 KeyAttribute 的最佳方法是什么?

我尝试使用DataAnnotationsModelMetadataProvider;但 ModelMetadata 不包含有关 KeyAttribute 的信息。

What is the best way to find which property has a KeyAttribute in provided Model (class)?

I tried with DataAnnotationsModelMetadataProvider; but ModelMetadata does not contain information about KeyAttribute.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

卖梦商人 2024-12-27 18:19:47

对于名为 MyModel 的模型类,您可以找到具有关键属性的属性,如下所示。

var keyAttributedProps = typeof(MyModel).GetProperties()
   .Where(p => p.GetCustomAttributes(typeof(KeyAttribute), true).Length == 1);

For a model class named MyModel, you can find the properties with key attributes as follows.

var keyAttributedProps = typeof(MyModel).GetProperties()
   .Where(p => p.GetCustomAttributes(typeof(KeyAttribute), true).Length == 1);
撩心不撩汉 2024-12-27 18:19:47

从未尝试过,但我认为您可以使用 TypeDescriptor.GetProperties 方法来获取所需的属性。根据 MSDN,它使用指定的属性数组作为过滤器返回指定组件的属性集合。

检查此链接。我希望它有帮助:
http://msdn.microsoft.com/en-us/library/3x9x2kh5 .aspx#Y0

Never tried, but i think you could use TypeDescriptor.GetProperties Method to get the dessired property. According with MSDN, it returns the collection of properties for a specified component using a specified array of attributes as a filter.

Check this link. I hope it helps:
http://msdn.microsoft.com/en-us/library/3x9x2kh5.aspx#Y0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文